使用未知字段/属性反序列化Json



我正在尝试使用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);

问题出现在动态生成的字段(例如2422424353533等)中。

根对象:

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; }
}

请让我知道如何在反序列化时识别它们。

不能将未定义的结构反序列化为已定义的结构。显然,这是不可能的,因为在运行时不能用新属性修改固定类。

匿名对象的帮助,示例来自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

链接到JSON.NET示例

相关内容

  • 没有找到相关文章

最新更新