解析JSON而不声明模型类

时间:2018-12-05 16:20:18

标签: c# .net json json.net

我有这样的JSON:

{
"bookings": {
    "group_id": "abc",
    "name": "Study Rooms",
    "url": "My URL",
    "timeslots": [{
            "room_id": "bcd",
            "room_name": "101",
            "booking_label": "Meeting1",
            "booking_start": "2018-11-30T07:00:00-06:00",
            "booking_end": "2018-11-30T07:30:00-06:00",
            "booking_created": "2018-11-28T11:32:32-06:00"
        }, {
            "room_id": "cde",
            "room_name": "102",
            "booking_label": "Meeting2",
            "booking_start": "2018-11-30T07:30:00-06:00",
            "booking_end": "2018-11-30T08:00:00-06:00",
            "booking_created": "2018-11-28T11:32:32-06:00"
        }, //##AND many more like this##
    ]
}
}

如果我尝试这样解析它:

var reservations = new { bookings = new { group_id = "", name = "", url="", timeslots = new List<Timeslot>() } };
Newtonsoft.Json.JsonConvert.PopulateObject(jsonResult, reservations);

仅填充时隙元素

但是,如果我声明具有属性groop_id,名称,URL和时隙集合的模型类,并进行如下解析:

var reservations = new { bookings = new BookingsModel() };
Newtonsoft.Json.JsonConvert.PopulateObject(jsonResult, reservations);

它工作正常。

问题是为什么,并且可以在不静态声明模型的情况下解析JSON的所有元素。

2 个答案:

答案 0 :(得分:3)

您无法填充匿名对象的原因是,在c#中,匿名类型为immutable

相反,您可以使用JsonConvert.DeserializeAnonymousType(),它将从现有实例中创建一个匿名类型的新实例:

var reservations = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(jsonResult, 
        new { bookings = 
            new { group_id = default(string), name = default(string), url=default(string), 
                 timeslots = default(List<Timeslot>) } });      

提琴here

答案 1 :(得分:0)

您的询问原因
group_id, 名称, 和URL arent越来越多?

它是因为其中没有实际值。

查看JsonSerializerSettings的参数