【问题标题】:Parse JSON without declaring model class解析 JSON 而不声明模型类
【发布时间】: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。

标签: c# .net json json.net


【解决方案1】:

您无法填充匿名对象的原因是,在 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.

【讨论】:

  • 谢谢!实际上这也有效:var rr = new { bookings = new { group_id = "", name = "", url="", timeslots = new List&lt;LibBookingTimeslot&gt;() } };var a = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonResult, rr.GetType());
【解决方案2】:

你问为什么
group_id, 姓名, 并且 url 没有被填充?

因为它没有实际价值。

查看JsonSerializerSettings的参数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-27
    • 2021-08-30
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    相关资源
    最近更新 更多