【发布时间】:2019-05-12 04:20:46
【问题描述】:
我有这样的 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、name、url 和 timeslots 集合的模型类,并像这样解析:
var reservations = new { bookings = new BookingsModel() };
Newtonsoft.Json.JsonConvert.PopulateObject(jsonResult, reservations);
效果很好。
问题是为什么,是否可以在不静态声明模型的情况下解析 JSON 的所有元素。
【问题讨论】:
-
没有时间解释原因,但请查看
Dynamic对象类型,docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/… -
@maccettura 我遇到过不得不使用它的用例,但总的来说我同意,c# 意味着进行静态类型检查
-
@SeanT "WHY" 是我问这个问题的原因:)
-
...and is it possible to parse all elements of JSON without static declaration of the model. -
@shlasasha - 你的 JSON 格式不正确:1) 最后的右大括号和括号的数量不正确。假设这是问题中的错误,我修复了它。 2) 像这样带有前导零的数字:
"room_id": 0001根据JSON standard 是无效的。为什么请参阅Why is JSON invalid if an integer begins with 0。 Json.NET 将这些解释为Octal,这对您没有帮助,您需要修复 JSON。