convert json to C# class
I want to convert the following to a C# class, can anyone help please? I have tried many different mutations but none can actually map the Params
to the class.
{
"method": "update",
"params": [
true,
{
"y": [
[
"3",
"5"
],
[
"1",
"2"
]
],
"x": [
[
"1",
"2"
],
[
"2",
"1"
]
],
"id": 1111,
"update": 164227,
"current": 164227
},
"TESTING"
],
"id": null
}
The following is what I could generate so far, but unfortunately, it can't map the Params
to the class, I want to get the values of X
and Y
in a list:
public class Data
{
[JsonProperty("method")]
public string Method { get; set; }
[JsonProperty("params")]
public List<ParamTest> Params { get; set; }
[JsonProperty("id")]
public object Id { get; set; }
}
public class ParamClass
{
[JsonProperty("x")]
public string[][] X { get; set; }
[JsonProperty("x")]
public string[][] Y { get; set; }
}
public struct ParamTest
{
public bool Bool;
public List<ParamClass> ParamClass;
public string String;
public static implicit operator ParamTest(bool Bool) => new ParamTest { Bool = Bool };
public static implicit operator ParamTest(List<ParamClass> ParamClass) => new ParamTest { ParamClass = ParamClass };
public static implicit operator ParamTest(string String) => new ParamTest { String = String };
}
Solution 1:
try this. It was tested in Visual Studio and working properly
var po = JObject.Parse(json);
Data data = new Data { Id = (string)po["id"], Method = (string)po["method"]
var pars = new ParamObject { };
foreach (var element in (JArray)po["params"])
{
var type = element.GetType().Name;
if (element.GetType().Name == "JValue")
{
if ((string)element == "TESTING")
pars.Testing = (string)element;
else pars.IsTrue = (bool)element;
}
else if (element.GetType().Name == "JObject")
{
pars.XYElement = element.ToObject<XYElement>();
}
}
data.Pars = pars;
classes
public partial class Data
{
[JsonProperty("method")]
public string Method { get; set; }
[JsonProperty("params")]
public ParamObject Pars { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
}
public partial class ParamObject
{
[JsonProperty("XYElement")]
public XYElement XYElement { get; set; }
[JsonProperty("IsTrue")]
public bool IsTrue { get; set; }
[JsonProperty("TESTING")]
public string Testing { get; set; }
}
public partial class XYElement
{
[JsonProperty("y")]
public List<List<long>> Y { get; set; }
[JsonProperty("x")]
public List<List<long>> X { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("update")]
public long Update { get; set; }
[JsonProperty("current")]
public long Current { get; set; }
}