解析JSON而不声明模型类 [英] Parse JSON without declaring model class
问题描述
我有这样的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##
]
}
}
如果我尝试这样解析它:
If I try to parse it like this:
var reservations = new { bookings = new { group_id = "", name = "", url="", timeslots = new List<Timeslot>() } };
Newtonsoft.Json.JsonConvert.PopulateObject(jsonResult, reservations);
仅填充时隙元素
但是,如果我声明一个具有groop_id,名称,URL和时隙集合属性的模型类,并进行如下解析:
However, if I declare a model class with properties groop_id, name, url, and timeslots collection, and parse like this:
var reservations = new { bookings = new BookingsModel() };
Newtonsoft.Json.JsonConvert.PopulateObject(jsonResult, reservations);
它工作正常.
问题是为什么,并且可以在不静态声明模型的情况下解析JSON的所有元素.
Question is WHY, and is it possible to parse all elements of JSON without static declaration of the model.
推荐答案
The reason that you are not able to populate your anonymous object is that, in c#, anonymous types are immutable.
相反,您可以使用 JsonConvert.DeserializeAnonymousType()
来创建来自现有实例的匿名类型的新实例:
Instead, you may use JsonConvert.DeserializeAnonymousType()
which will create a new instance of your anonymous type from your existing instance:
var reservations = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(jsonResult,
new { bookings =
new { group_id = default(string), name = default(string), url=default(string),
timeslots = default(List<Timeslot>) } });
样本小提琴此处.
这篇关于解析JSON而不声明模型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!