【问题标题】:Get partial object list from JSON C#从 JSON C# 获取部分对象列表
【发布时间】:2016-03-22 02:23:06
【问题描述】:

我在 C# 中调用一个 RESTful 服务,结果类似这样:

{
  "blabla":1,
  "bbb":false,
  "blabla2":{
    "aaa":25,
    "bbb":25,
    "ccc":0
  },
  "I_want_child_list_from_this":{
     "total":15226,
     "max_score":1.0,
     "I_want_this":[
       {
        "A":"val1",
        "B":"val2",
        "C":"val3"
       },
       {
        "A":"val1",
        "B":"val2",
        "C":"val3"
       }
       ...
      ]
  "more_blabla": "fff"
  ... 
}

我想将“I_want_this”部分作为listobjectJObject 有没有类似

(JObject)responseString["I_want_child_list_from_this"]["I_want_this"]

更笼统地说:

(JObject)responseString["sub"]["sub_sub"]

我正在使用Newtonsoft.Json

谢谢!

【问题讨论】:

  • 您使用的是哪个 JSON 解析器?牛顿软件?
  • 是的,使用Newtonsoft.Json
  • 感谢@Gomes 您的评论让我更接近当前的解决方案。你可以让它成为一个答案,我接受它。谢谢!
  • @DDan 根据您的要求完成,如果它解决了您的问题,我很高兴 :)

标签: c# json rest json.net


【解决方案1】:

首先,我将创建一个表示从服务调用返回的 JSON 结构的类。 (http://json2csharp.com/ 从 JSON 自动生成类的好工具)

其次,如果您不使用 Newtonsoft.Json 库,我建议您使用该库。

最后,使用 Newtonsoft 将 JSON 从服务调用反序列化到您创建的类中:

var json = Service.GetJson();
var yourDesiralizedJson = JsonConvert.DeserializeObject<YourJsonToCSharpClass>(json);
var listYouWant = yourDesiralizedJson.IWantChildList.IWantThis;

【讨论】:

  • 谢谢,这看起来很理想,但是我没有结果类型的通用结构,这就是为什么我期待 objects 或 JObjects
【解决方案2】:

以下链接似乎接近解决方案,因为请求者使用 NewtonSoft.Json 作为其 api 来操作对象。也感谢其他用户的解决方案。

看看例如这里 newtonsoft.com/json/help/html/SerializingJSONFragments.htm

【讨论】:

  • 你能总结一下这里的信息吗?仅链接的答案容易损坏,有时甚至会被标记和删除。
【解决方案3】:

按照 ertdiddy 的建议,最好的解决方案 (imo) 是定义描述 JSON 模式的类,然后使用 DeserializeObject。作为一种捷径,您可以使用 DeserializeAnonymousType 与您的架构的不完整定义,利用 JSON 的宽大处理。在你的情况下,这段代码对我有用:

        var testDataFromQuestion = @"
{
  ""blabla"":1,
  ""bbb"":false,
  ""blabla2"":{
    ""aaa"":25,
    ""bbb"":25,
    ""ccc"":0
  },
  ""I_want_child_list_from_this"":{
     ""total"":15226,
     ""max_score"":1.0,
     ""I_want_this"":[
       {
        ""A"":""val1"",
        ""B"":""val2"",
        ""C"":""val3""
       },
       {
        ""A"":""val1"",
        ""B"":""val2"",
        ""C"":""val3""
       }
      ],
  ""more_blabla"": ""fff""
}";

        var anonymousDefinitionOfJson = new {
           I_want_child_list_from_this = new {
               I_want_this = new Dictionary<string, string>[] {}
           }
        };
        var fullDeserializationOfTestData =
           JsonConvert.DeserializeAnonymousType(testDataFromQuestion,
                                                anonymousDefinitionOfJson);
        var stuffYouWant = insterestingBits.I_want_child_list_from_this.I_want_this;
        Console.WriteLine($"The first thing I want is {stuffYouWant[0]["A"]}");

这将输出预期值“val1”。我匿名定义了只获取您想要的数据的最小类,然后我要求 Newtonsoft 解析足以填充这些类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    相关资源
    最近更新 更多