C# Merge JSONs

In this tutorial we will learn how to merge two JSONs in C#, using the Json.NET library.

Introduction

In this tutorial we will learn how to merge two JSONs in C#, using the Json.NET library. If you are using Visual Studio, you can easily install it from the NuGet Package Manager.

This tutorial was tested with .NET Core 3.1 and with version 12.03 of the Json.NET library.

Merging JSONs

As usual, we will start by stating the namespaces used. We will need to use the Newtonsoft.Json.Linq namespace, so we have access to the class we need to merge the JSONs. We will also use the System namespace to be able to print the result to the console.

using Newtonsoft.Json.Linq;
using System;

Moving on to the Main function, we will declare two JSON strings. Each one will contain different properties, so we can get a single JSON at the end, resulting from the merge operation.

The first one will contain a property called name and another called age. The second will contain a property called language and another called married. Thus, it is expected that the resulting JSON contains these 4 properties and the corresponding values.

var jsonString1 = @"{
     ""name"": ""Tod"",
     ""age"": 20 
}";

var jsonString2 = @"{
    ""language"": ""English"",
    ""married"": true 
}";

After this, we will parse both strings to objects of class JObject. In essence, a JObject represents a JSON object [1].

To do so, we simply need to call the static Parse method from the JObject class, passing as input the JSON string. As output, this method returns the parsed JObject.

var jObject1 = JObject.Parse(jsonString1);
var jObject2 = JObject.Parse(jsonString2);

Additionally, we will create an empty JObject, which we will use as output of the operation. This will avoid mutating our original JObjects. Nonetheless, if this is not a requirement, one of the original JSONs could also be used as result of the merging operation.

var result = new JObject();

To perform the merge, we simply need to call the Merge method on our result JObject, passing as input one of the parsed JObjects. Then, we will call the method again, passing as input the second parsed JObject.

result.Merge(jObject1);
result.Merge(jObject2);

To finalize, we will print the result to the console.

Console.WriteLine(result);

The complete code can be seen below.

namespace JsonMerge
{
    using Newtonsoft.Json.Linq;
    using System;

    class Program
    {
        static void Main(string[] args)
        {
            var jsonString1 = @"{
                ""name"": ""Tod"",
                ""age"": 20 
            }";

            var jsonString2 = @"{
                ""language"": ""English"",
                ""married"": true 
            }";

            var jObject1 = JObject.Parse(jsonString1);
            var jObject2 = JObject.Parse(jsonString2);

            var result = new JObject();

            result.Merge(jObject1);
            result.Merge(jObject2);

            Console.WriteLine(result);
        }
    }
}

Upon compiling and running the code, you should get a result similar to figure 1.

Output of the merge operation.
Figure 1 – Output of the merge operation.

Additional use case

To finish this tutorial, we are going to analyze a use case where we will have a string property with the same name in both JSONs.

The complete code can be seen below. It is exactly what we have seen before, but with a property called name existing in both JSONs.

namespace JsonMerge
{
    using Newtonsoft.Json.Linq;
    using System;

    class Program
    {
        static void Main(string[] args)
        {
            var jsonString1 = @"{
                ""name"": ""Tod"",
                ""age"": 20 
            }";

            var jsonString2 = @"{
                ""name"": ""Jake"",
                ""married"": true 
            }";

            var jObject1 = JObject.Parse(jsonString1);
            var jObject2 = JObject.Parse(jsonString2);

            var result = new JObject();

            result.Merge(jObject1);
            result.Merge(jObject2);

            Console.WriteLine(result);
        }
    }
}

If we compile and run the previous code, we get the output shown on figure 2. As can be seen below, we only get a name property in the merged JSON, which corresponds to the value of the last JSON merged.

Output of the merging with the same property in both original JSONs.
Figure 2 – Output of the merging with the same property in both original JSONs.

Note however that this behavior will differ if the properties with the same name in both JSONs are arrays or objects. In that case, their content will be merged instead of overridden.

The merging behavior can be changed by passing as additional parameter of the merge method an object of class JsonMergeSettings.

References

[1] https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm

1 thought on “C# Merge JSONs”

  1. It works with one item in each string, but add 20 or more and it doesn’t work. Besides, show an example that reads two json files from disk.

Leave a Reply

Discover more from techtutorialsx

Subscribe now to keep reading and get access to the full archive.

Continue reading