Merge two JTokens into one
You can use JContainer.Merge(Object, JsonMergeSettings)
to merge one JObject
onto another. Note that JsonMergeSettings.MergeArrayHandling
gives control over how arrays are merged. From the MergeArrayHandling
Enumeration documentation, the possible merge options are:
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.
Thus merging using MergeArrayHandling.Concat
as follows, where allPages
and pageOne
are both of type JContainer
(or a subclass, such as 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;
gives:
{
"data": [
{
"ID": "53a1862000404a304942546b35519ba3",
"name": "Private Approval Process: Draft Document CPL",
"objCode": "ARVPTH"
},
{
"ID": "53a1838200401324eb1ec66562e9d77d",
"name": "Private Approval Process: Draft Document CPL",
"objCode": "ARVPTH"
}
]
}
While merging using Replace
gives:
{
"data": [
{
"ID": "53a1838200401324eb1ec66562e9d77d",
"name": "Private Approval Process: Draft Document CPL",
"objCode": "ARVPTH"
}
]
}
If your variables are of type JToken
you will need to cast them to JContainer
. (JSON primitives that are not containers cannot be merged.)
JsonMergeSettings.MergeNullValueHandling
gives control over whether to merge or ignore null
values, as required.