将两个JToken合并为一个
如何将这两个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;
回答:
您可以JContainer.Merge(Object,
JsonMergeSettings)用来将一个合并JObject
到另一个。请注意,可以JsonMergeSettings.MergeArrayHandling
控制数组的合并方式。从MergeArrayHandling
Enumeration文档中,可能的合并选项是:
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
如下,其中allPages
和pageOne
均为类型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.MergeNullValueHandling
null
根据需要控制是合并还是忽略值。
以上是 将两个JToken合并为一个 的全部内容, 来源链接: utcz.com/qa/411214.html