我正在尝试将跟随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; }
}
答案 0 :(得分:1)
您可以将json数据转换为动态对象。
Json.Net
dynamic entity = JsonConvert.DeserializeObject(jsonstring);
然后像这样访问
dynamic entity1 = entity.WANConnectionDevice.1;
答案 1 :(得分:0)
要反序列化JSON对象而不为每个对象创建一个类,可以使用JsonObject类。更多信息:https://msdn.microsoft.com/en-us/library/system.json.jsonobject(v=vs.95).aspx