将复杂的JSON反序列化为c#对象
本文关键字:对象 反序列化 JSON 复杂 | 更新日期: 2023-09-27 18:01:44
我试图将以下JSON反序列化为c#对象。但是,我试图在不为"1"
对象创建类的情况下实现这一点。这只是我将要处理的JSON的一小段,一些JSON对象将包含多达40个子对象,这意味着我将不得不复制大量代码。
是否有一种方法可以将这种风格的JSON反序列化为c#对象,而无需为1,2等创建类?
{
"WANConnectionDevice": {
"1": {
"WANPPPConnection": {
"1": {
"ExternalIPAddress": {
"_value": "0.0.0.0",
"_timestamp": "2016-08-04T08:51:37.813Z",
"_type": "xsd:string",
"_writable": false
},
"Password": {
"_writable": true,
"_timestamp": "2016-08-02T10:40:35.134Z",
"_value": "test6",
"_type": "xsd:string"
},
"Username": {
"_writable": true,
"_timestamp": "2016-08-02T10:40:35.134Z",
"_value": "test6@test.net",
"_type": "xsd:string"
},
"MACAddress": {
"_writable": false,
"_timestamp": "2016-08-02T16:48:15.188Z",
"_value": "",
"_type": "xsd:string"
}
}
}
},
"2": {
"WANIPConnection": {
"1": {
"ExternalIPAddress": {
"_writable": true,
"_timestamp": "2016-08-02T16:48:15.188Z",
"_value": "",
"_type": "xsd:string"
},
"MACAddress": {
"_writable": false,
"_timestamp": "2016-08-02T16:48:15.188Z",
"_value": "",
"_type": "xsd:string"
}
}
}
}
}
}
下面是一些类的例子,我可以让它反序列化到不实用或不好的设计,这是我希望避免的。
public class _1
{
public ExternalIPAddress ExternalIPAddress { get; set; }
public Password Password { get; set; }
public Username Username { get; set; }
public MACAddress MACAddress { get; set; }
}
public class WANPPPConnection
{
public _1 _1 { get; set; }
}
public class _1
{
public WANPPPConnection WANPPPConnection { get; set; }
}
public class WANIPConnection
{
public _1 { get; set; }
}
public class _2
{
public WANIPConnection WANIPConnection { get; set; }
}
可以将json数据转换为动态对象。
与<<p> strong> Json。dynamic entity = JsonConvert.DeserializeObject(jsonstring);
然后像这样访问
dynamic entity1 = entity.WANConnectionDevice.1;
要反序列化JSON对象而不为每个对象创建类,可以使用JsonObject类。更多信息在这里:https://msdn.microsoft.com/en-us/library/system.json.jsonobject(v=vs.95).aspx