Parse JSON without declaring model class

我与影子孤独终老i 提交于 2020-01-14 05:21:10

问题


I have JSON like this:

{
"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);

Only timeslots element gets populated

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

It works fine.

Question is WHY, and is it possible to parse all elements of JSON without static declaration of the model.


回答1:


The reason that you are not able to populate your anonymous object is that, in c#, anonymous types are immutable.

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

Sample fiddle here.




回答2:


your asking why
group_id, name, and url arent getting populated?

its because theres no actual value in it.

look at the parameter for JsonSerializerSettings



来源:https://stackoverflow.com/questions/53636516/parse-json-without-declaring-model-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!