c#json列表反序列化
本文关键字:反序列化 列表 c#json | 更新日期: 2023-09-27 18:28:08
具有以下类:
[DataContract]
public class TestDynamicJSON1
{
public TestDynamicJSON1()
{
this.TO2_List = new List<TestDynamicJSON2>();
}
[DataMember]
public int A { get; set; }
[DataMember]
public string B { get; set; }
[DataMember]
public DateTime C { get; set; }
[DataMember]
public List<TestDynamicJSON2> TO2_List { get; set; }
}
[DataContract]
public class TestDynamicJSON2
{
public TestDynamicJSON2()
{
}
[DataMember]
public int A2 { get; set; }
[DataMember]
public string B2 { get; set; }
[DataMember]
public DateTime C2 { get; set; }
}
[DataContract]
public class TestDynamicJSON2_1 : TestDynamicJSON2
{
public TestDynamicJSON2_1()
{
}
}
[DataContract]
public class TestDynamicJSON2_2 : TestDynamicJSON2
{
public TestDynamicJSON2_2()
{
}
}
[DataContract]
public class TestDynamicJSON2_3 : TestDynamicJSON2
{
public TestDynamicJSON2_3()
{
}
}
在服务器端将对象转换为JObject:
public JObject GetDynamicJO()
{
TestDynamicJSON1 TO = new Metadata.CatalogManagement.TestDynamicJSON1();
TO.A = 1;
TO.B = "2";
TO.C = DateTime.Now;
TestDynamicJSON2_1 TO2_1 = new Metadata.CatalogManagement.TestDynamicJSON2_1();
TO2_1.A2 = 11;
TO2_1.B2 = "22";
TO2_1.C2 = DateTime.Now;
TO.TO2_List.Add(TO2_1);
TestDynamicJSON2_2 TO2_2 = new Metadata.CatalogManagement.TestDynamicJSON2_2();
TO2_2.A2 = 11;
TO2_2.B2 = "22";
TO2_2.C2 = DateTime.Now;
TO.TO2_List.Add(TO2_2);
TestDynamicJSON2_3 TO2_3 = new Metadata.CatalogManagement.TestDynamicJSON2_3();
TO2_3.A2 = 11;
TO2_3.B2 = "22";
TO2_3.C2 = DateTime.Now;
TO.TO2_List.Add(TO2_3);
JProperty property1 = new JProperty("DO", JToken.FromObject(TO));
JObject jo = new JObject(property1);
return jo;
}
在客户端尝试反序列化:
var str = await response1.Content.ReadAsStringAsync();
var jo = JsonConvert.DeserializeObject<TestDynamicJSON1>(str);
Json字符串如下:
{"DO":{"A":1,"B":"2","C":"2015-12-24T19:42:51.6509893+04:00","TO2_List":[{"A2":11,"B2":"22","C2":"2015-12-24T19:42:51.6509893+04:00"},{"A2":11,"B2":"22","C2":"2015-12-24T19:42:51.6509893+04:00"},{"A2":11,"B2":"22","C2":"2015-12-24T19:42:51.6509893+04:00"}]}}
并且list TO2_list属性为空。是因为它是基类的列表吗?
你能帮忙吗?
谢谢。
您的类应该是这样的。
public class TO2List
{
public int A2 { get; set; }
public string B2 { get; set; }
public string C2 { get; set; }
}
public class DO
{
public int A { get; set; }
public string B { get; set; }
public string C { get; set; }
public List<TO2List> TO2_List { get; set; }
}
public class RootObject
{
public DO DO { get; set; }
}
您可以通过这种方式绑定值。
var str = await response1.Content.ReadAsStringAsync();
var jo = JsonConvert.DeserializeObject<RootObject>(str);
你可以通过这种方式获得价值
//jo.DO.A