问题
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