【问题标题】:Discard items when deserializing Json collection with Json.net使用 Json.net 反序列化 Json 集合时丢弃项目
【发布时间】:2014-01-02 16:54:41
【问题描述】:

我有一个 JSON 流,它发送如下所示的集合:

[{"channel":"24e67e0d-1cad-4cc09e7af8523ef460fe",     
  "op":"private", 
  "origin":"broadcast", 
  "stamp":1388680103991749},
"13886801043507640",
"24e67e0d-1cad-4cc0-9e7a-f8523ef460fe"]

第一个对象没有问题,但最后两个对象("13886801043507640""24e67e0d-1cad-4cc0-9e7a-f8523ef460fe")使Json.Net 抛出异常,它们甚至不遵循{field:name,field:name} 的格式。

如何使用Json.Net 正确处理这些对象(或至少丢弃它们)?

干杯,感谢任何意见。

【问题讨论】:

    标签: c# .net json json.net deserialization


    【解决方案1】:

    这是使用 Json.Net 从 JSON 中提取对象数据的一种方法。

    首先为对象定义一个类:

    class Item
    {
        public string channel { get; set; }
        public string op { get; set; }
        public string origin { get; set; }
        public long stamp { get; set; }
    }
    

    然后使用Json.Net的LINQ-to-JSON API对数组进行解析过滤,只提取对象部分:

    JArray array = JArray.Parse(json);
    Item item = array.Children<JObject>().First().ToObject<Item>();
    

    如果可以有多个对象,您可以将它们放入这样的列表中(假设它们都具有相同的结构):

    List<Item> items = array.Children<JObject>()
                            .Select(jo => jo.ToObject<Item>())
                            .ToList();
    

    同样,您可以像这样从数组中获取字符串值:

    List<string> strings = array.Children<JValue>()
                                .Select(jv => jv.ToString())
                                .ToList();
    

    【讨论】:

    • 感谢 Brian 的清晰答案,它就像一个魅力。
    • 没问题;很高兴为您提供帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    相关资源
    最近更新 更多