C#JObject没有正确嵌套

时间:2016-07-29 20:57:24

标签: c# json formatting json.net

我正在处理合并我的json数组的一些问题。要合并的原始数组看起来类似于:

{
  "ads":[
    {
      "a1": "b1",
      "i1": "j1",
      "x1": "y1",
    }
  ]
}

{
  "ads": [
    {
      "a2": "b2",
      "i2": "j2",
      "x2": "y2",
    }
  ]
}

我的合并结果与此类似:

{
  "ads:[
    [
      {
        "a1": "b1",
        "i1": "j1",
        "x1": "y1",
      }
    ],
    [
      {
        "a2": "b2",
        "i2": "j2",
        "x2": "y2",
      }
    ]
  ]
}

我想把它简化为:

{
  "ads:[
    {
      "a1": "b1",
      "i1": "j1",
      "x1": "y1",
    },
    {
      "a2": "b2",
      "i2": "j2",
      "x2": "y2",
    }
  ]
}

目前用于尝试合并两者的代码是:

        // Combine all ads within formattedContent into one single JOBject.
        JToken token = null;
        JArray jarray = new JArray();
        List<JToken> jtokens = new List<JToken>();
        foreach (JObject jobject in formattedContent)
        {
            token = JToken.Parse(jobject.SelectToken("ads").ToString());                
            jarray.Add(token);
        }

但是当最终产品需要在一个阵列下的“ads”标记中产生所有广告时,我会遇到双嵌套数组。请注意,上面代码中的formattedContent是List<JObject>。任何合并json数组的帮助都将受到赞赏。在将标记添加到JArray之前尝试将标记添加到字符串会导致添加回车符和转义字符。(这些不是仅在调试器视图中添加[正如我经常看到的那样],它们实际上是反映在最终产品中)

1 个答案:

答案 0 :(得分:0)

您要做的是将token.Children()而不是token添加到jarray(即添加token而不是token本身的内容):

var jarray = new JArray();
foreach (var jobject in formattedContent)
{
    var token = jobject.SelectToken("ads") as JArray;
    if (token != null)
        jarray.Add(token.Children());
}

顺便说一句,您可以使用JContainer.Merge()在根对象上实现相同的效果,设置为JsonMergeSettings.MergeArrayHandling = MergeArrayHandling.Concat

var merged = new JObject();
var settings = new JsonMergeSettings
{
    MergeArrayHandling = MergeArrayHandling.Concat,
};
foreach (var jobject in formattedContent)
{
    merged.Merge(jobject, settings);
}