简体   繁体   English

在C#中解析动态变化的json文件

[英]parsing a dynamically changing json file in c#

I am calling a webservice which returns the response in json in the following format. 我正在调用一个Web服务,该服务以以下格式返回json中的响应。

{
  "parent": 
    {
      "child": {
        "key1": value1,
        "key2": value2
      }
    }  
}

The above reponse is when there is only one child in the parent. 上面的答复是当父母中只有一个孩子时。 But when there are more than one child in parent, then the response is as shown: 但是,当父母中有多个孩子时,响应如下所示:

{
  "parent": [
    {
      "child": {
        "key1": "value1",
        "key2": "value2"
      }
    },
    {

      "child": {
        "key1": "value1",
        "key2": "value2"
      }
    }
  ]
}

Thus when there are more than one child elements, the parent is a JArray and when there is only child element, the parent is JObject. 因此,当有多个子元素时,父元素是JArray,而只有子元素时,父元素是JObject。

Now I am having difficulty in parsing the contents of the child elements dynamically as it throws error of index when it is JObject. 现在,我很难动态地解析子元素的内容,因为当它是JObject时会抛出索引错误。

Can someone explain how we can parse the contents both during JObject and JArray. 有人可以解释一下我们如何在JObject和JArray中解析内容。

Currently I am checking the parent tag as whether it is JObject/ JArray and correspondingly parsing, but it is a long and tedious process. 目前,我正在检查父标记是否为JObject / JArray并进行相应的解析,但这是一个漫长而乏味的过程。

Is there any other method for the same. 是否有任何其他方法可以相同。

Following is code that I am using now 以下是我现在正在使用的代码

if(jsonfile["parent"].getType() == "JObject")
{
   string value1 = (string)jsonfile["parent"]["child"]["key1"]
}
else
{
   string value1 = (string)jsonfile["parent"][0]["child"]["key1"];
}

Is there any other method where we can get value1 without checking whether parent is JObject or JArray? 还有其他方法可以在不检查父对象是JObject还是JArray的情况下获取value1吗?

You could introduce an extension method such as 您可以引入扩展方法,例如

public static class JsonExtensions
{
    public static IEnumerable<JToken> SingleOrArrayItems(this JToken source)
    {
        if (source == null || source.Type == JTokenType.Null)
            return Enumerable.Empty<JToken>();
        IEnumerable<JToken> arr = source as JArray;
        return arr ?? new[] { source };
    }
}

And then do: 然后执行:

var child = jsonfile["parent"].SingleOrArrayItems().FirstOrDefault();
var value1 = child == null ? null : child.SelectToken("child.key1");

Or you could use SelectTokens() with the JSONPath recursive descent operator .. taking the place of the optional array index: 或者,您可以将SelectTokens()JSONPath递归下降操作符.. ,以代替可选的数组索引:

var value1 = jsonfile.SelectTokens("parent..child.key1").FirstOrDefault();

Sample fiddle . 样品提琴

(Questions about how to handle this sort of polymorphic JSON show up quite often; see for instance How to handle both a single item and an array for the same property using JSON.net for a way to deserialize JSON like this to fixed POCO types.) (有关如何处理这种多态JSON的问题经常出现;例如,请参阅如何使用JSON.net处理相同属性的单个项目和数组,以解决将JSON反序列化为固定POCO类型的方法。 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM