小编典典

将两个JToken合并为一个

json

如何将这两个JToken合并为一个JToken。听起来应该很简单,但无法解决。

{
  "data":[
  {
      "ID":"53a1862000404a304942546b35519ba3",
      "name":"Private Approval Process: Draft Document CPL",
      "objCode":"ARVPTH"
  }]
}

{
"data":[
  {
      "ID":"53a1838200401324eb1ec66562e9d77d",
      "name":"Private Approval Process: Draft Document CPL",
      "objCode":"ARVPTH"
  }]
}

谢谢您的帮助!

到目前为止,这是我尝试过的:

我首先将第一个对象分配给变量,Jtoken pageOne然后尝试将其连接到第二个变量JToken allPages。我有一个循环,可以带回具有三个字段的多个页面。最终目标是抓取每个页面并创建一个Token包含所有页面的大J。

像这样的东西:

for (int page = 0; page <= recCount; page += 2000)
{
 //Get data
 pageOne = getJsonData();
 allPages.Concat(pageOne);
}
return allPages;

阅读 531

收藏
2020-07-27

共1个答案

小编典典

您可以JContainer.Merge(Object, JsonMergeSettings)用来将一个合并JObject到另一个。请注意,可以JsonMergeSettings.MergeArrayHandling控制数组的合并方式。从MergeArrayHandlingEnumeration文档中,可能的合并选项是:

 Concat  0   Concatenate arrays.
 Union   1   Union arrays, skipping items that already exist.
 Replace 2   Replace all array items.
 Merge   3   Merge array items together, matched by index.

因此,使用合并MergeArrayHandling.Concat如下,其中allPagespageOne均为类型JContainer(或子类,例如JObject):

JContainer allPages = null;
var settings = new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Concat };
for (int page = 0; page <= recCount; page += 2000)
{
    //Get data
    var pageOne = (JContainer)getJsonData(page);
    if (allPages == null)
        allPages = pageOne;
    else
        allPages.Merge(pageOne, settings);
}
return allPages;

给出:

{
  "data": [
    {
      "ID": "53a1862000404a304942546b35519ba3",
      "name": "Private Approval Process: Draft Document CPL",
      "objCode": "ARVPTH"
    },
    {
      "ID": "53a1838200401324eb1ec66562e9d77d",
      "name": "Private Approval Process: Draft Document CPL",
      "objCode": "ARVPTH"
    }
  ]
}

合并使用时Replace给出:

{
  "data": [
    {
      "ID": "53a1838200401324eb1ec66562e9d77d",
      "name": "Private Approval Process: Draft Document CPL",
      "objCode": "ARVPTH"
    }
  ]
}

如果您的变量是类型JToken,则需要将其强制转换为JContainer。(不是容器的JSON原语不能合并。)

JsonMergeSettings.MergeNullValueHandlingnull根据需要控制是合并还是忽略值。

2020-07-27