Reputation: 147
I am trying to deserialize the follow JSON to C# objects. However, I am trying to achieve this without creating classes for the "1"
objects. This is just a small snippet of the JSON that I will be processing and some of the JSON objects will contain up to 40 child objects, meaning I would have to duplicate a lot of code.
Is there a way to deserialize this style JSON to C# objects without creating classes for 1, 2, etc.?
{
"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": "[email protected]",
"_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"
}
}
}
}
}
}
Here is an example of the some of the classes that I can get it to deserialize to which is not practical or good design and what I am hoping to avoid.
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; }
}
Upvotes: 0
Views: 330
Reputation: 402
You can convert json data to dynamic object.
with Json.Net
dynamic entity = JsonConvert.DeserializeObject(jsonstring);
then access like this
dynamic entity1 = entity.WANConnectionDevice.1;
Upvotes: 1
Reputation: 1235
To deserialize JSON objects without create a class for each of them, you can use JsonObject class. More info here: https://msdn.microsoft.com/en-us/library/system.json.jsonobject(v=vs.95).aspx
Upvotes: 0