我试图使用Newtonsoft.Json反序列化以下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#代码:
var data = JsonConvert.DeserializeObject<Rootobject>(jsonSource);
问题出现在2422424,353533等动态生成的字段中。
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; }
}
请在反序列化时告诉我如何识别它们。
答案 0 :(得分:1)
您无法将未定义的结构反序列化为已定义的结构。显然这是不可能的,因为在运行时不能使用新属性修改固定类。
帮助的匿名对象,来自JSON.NET的文档示例:
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