How to Merge Two Jobject

How to merge two json documents in json.net?

The JSON.NET documentation has an article just for that: Merging JSON. You can use JObject.Merge to merge two different objects into one:

JObject o1 = JObject.Parse(@"{
'FirstName': 'John',
'LastName': 'Smith',
'Enabled': false,
'Roles': [ 'User' ]
}");
JObject o2 = JObject.Parse(@"{
'Enabled': true,
'Roles': [ 'User', 'Admin' ]
}");

o1.Merge(o2, new JsonMergeSettings
{
// union array values together to avoid duplicates
MergeArrayHandling = MergeArrayHandling.Union
});

What you posted is two objects. A JSON document may be text, but what it contains are arrays and objects. "Merging" means finding a way to combine those objects/arrays and produce a new array or object.

Merge is defined by JContainer, the parent of both JObject and JArray. This means you can use Merge to merge both arrays and objects.

Another option with arrays is to use Enumerable.Union to combine the contents of both arrays, and create a new one :

var array1= JArray.Parse("[1,2,3]");
var array2= JArray.Parse("[3,4,5, \"a\"]");

var array3=new JArray(array1.Union(array2));

This returns [1,2,3,4,5,"a"]

How can I merge two JObject?

JArray dataOfJson1=json1.SelectToken("data");

JArray dataofJson2=json2.SelectToken("data");

foreach(JObject innerData in dataofJson2)
{
dataOfJson1.Add(innerData);
}

How do I merge multiple json objects

var jObject1 = // Your first json object as JObject
var jObject2 = // Your second json object as JObject
jObject1.Merge(jObject2);

System.Text.Json Merge two objects

As of .Net Core 3.0 merging of JSON objects is not implemented by System.Text.Json:

  • There are no Merge or Populate methods on JsonDocument.

  • There are no Merge or Populate methods on JsonSerializer.

More generally, JsonDocument is read-only. It

Provides a mechanism for examining the structural content of a JSON value without automatically instantiating data values.

As such it isn't designed to support modifying a JSON value in any way including merging another JSON value into it.

There is currently an enhancement request to implement a modifiable JSON Document Object Model:
Issue #39922: Writable Json DOM. It has an associated specification Writable JSON Document Object Model (DOM) for System.Text.Json. If this enhancement were implemented, merging of JSON documents would become possible. You could add an issue requesting functionality equivalent to JContainer.Merge(), linking back to Issue #39922 as a prerequisite.

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.

How to Merge 2 JSON strings C#

If I got your point, You don't have a concreate class to serialize or de-serilize your data because it is dynamic.

Then what I can suggest is to use the C#'s built in support for 'dynamic' types. Once you convert a JSON string to dynamic, It became an instance of dynamic and will be considered as an object. This object you can pass to your browser

  1. Imagine you got data as plan string from your database
  2. De-Serialize it down to a 'dynamic' object. A dynamic object can have any structure and datatype
  3. Once you de-serialize it to a dynamic variable, You can attach the instance to your server response and sent to client. It will be in an object form when it reaches the client

Here's an example

A. Deserialize to dynamic

dynamic results = JsonConvert.DeserializeObject<dynamic>(YOUR_JSON);

B. Add one more item to your response class/contract

    [DataContract]
internal class message {
[DataMember]
public dynamic data;
}

C. Return to client

message msg = new message();
msg.data = results;

UPDATE AFTER COMMENTS

Try this

using Newtonsoft.Json;

public class Program
{
public static void Main(string[] args)
{
// NOTE JSON now valid.
string strJSON = "[ { \"id\": 1, \"name\": \"William\" }, { \"id\": 2, \"name\": \"Dylan\" } ] ";
dynamic results = JsonConvert.DeserializeObject<dynamic>(strJSON);

var msg = new Message();
msg.Html = "<h1>Hello</h1><p>World</p>";
msg.Title = "Test";
msg.Status = "Success";
msg.Data = results;

string output = JsonConvert.SerializeObject(msg);
Console.WriteLine(output);

Console.ReadLine();
}

public class Message
{
public string Html { get; set; }
public string Title { get; set; }
public string Status { get; set; }
public dynamic Data { get; set; }
}
}

Output

Sample Image

Merge two Json.NET arrays by concatenating contained elements

JToken.FromObject(x.Concat(x))


Related Topics



Leave a reply



Submit