[英]convert json to C# class
我想将以下内容转换为C#
class,有人可以帮忙吗? 我尝试了许多不同的突变,但实际上没有一个可以将 map Params
转换为 class。
{
"method": "update",
"params": [
true,
{
"y": [
[
"3",
"5"
],
[
"1",
"2"
]
],
"x": [
[
"1",
"2"
],
[
"2",
"1"
]
],
"id": 1111,
"update": 164227,
"current": 164227
},
"TESTING"
],
"id": null
}
以下是我到目前为止可以生成的内容,但不幸的是,它不能 map 到 class 的Params
,我想在列表中获取 X 和 Y 的值:
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 };
}
由于非结构化数据结构,必须使用Object
进行反序列化。
使用以下类
public class JsonData
{
public string Method { get; set; }
public List<Object> Params { get; set; }
public int? ID { get; set; }
}
public class Params
{
public string[][] X { get; set; }
public string[][] Y { get; set; }
}
然后现在使用
var data = JsonConvert.DeserializeObject<JsonData>(json);
var paramsData = JsonConvert.DeserializeObject<Params>(data.Params[1].ToString());
尝试这个。 它在 Visual Studio 中测试并正常工作
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;
班级
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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.