Reputation:
I'm trying to deserialize the following Json using Newtonsoft.Json.
Json:
{
"response":{
"lines":{
"day":{
"day_data":{
"available":1,
"rating":"1"
},
"2422424":{
"data_id":"2422424",
"category":"breakfast"
}
},
"night":{
"night_data":{
"available":2,
"rating":"2"
},
"353533":{
"line_id":"353533",
"category":"dinner"
},
"3433":{
"line_id":"3433",
"category":"dinner"
}
}
}
}
}
C# Code:
var data = JsonConvert.DeserializeObject<Rootobject>(jsonSource);
The problem arises with the fields such as 2422424,353533 etc which are generated dynamically.
RootObject:
public class Rootobject
{
public Response response { get; set; }
}
public class Response
{
public Lines lines { get; set; }
}
public class Lines
{
public Day day { get; set; }
public Night night { get; set; }
}
public class Day
{
public Day_Data day_data { get; set; }
public _2422424 _2422424 { get; set; }
}
public class Day_Data
{
public int available { get; set; }
public string rating { get; set; }
}
public class _2422424
{
public string data_id { get; set; }
public string category { get; set; }
}
public class Night
{
public Night_Data night_data { get; set; }
public _353533 _353533 { get; set; }
public _3433 _3433 { get; set; }
}
public class Night_Data
{
public int available { get; set; }
public string rating { get; set; }
}
public class _353533
{
public string line_id { get; set; }
public string category { get; set; }
}
public class _3433
{
public string line_id { get; set; }
public string category { get; set; }
}
Please let me know how to identify them while deserializing.
Upvotes: 1
Views: 2986
Reputation: 10347
You can not deserialize an undefined structure into a defined structure. Obviously this is not possible as fixed classes cannot be amended with new properties at runtime.
Anonymous objects to the help, sample from JSON.NET's documentation:
var definition = new { Name = "" };
string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);
Console.WriteLine(customer1.Name);
// James
string json2 = @"{'Name':'Mike'}";
var customer2 = JsonConvert.DeserializeAnonymousType(json2, definition);
Console.WriteLine(customer2.Name);
// Mike
Upvotes: 2