Merging JSON with Newtonsoft Json.NET

Sat May 22 2021Software Development

I had recently wanted to enrich a datasource with some preconfigured metadata. In order to this I used the Newtonsoft Json.NET library.

The unit test demo below contains an example that can take a JSON string or by taking C# objects.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Diagnostics;

namespace JsonMerge
{
    [TestClass]
    public class MergeTest
    {
        public class Person
        {
            public Person(string name, int age)
            {
                Title = name;
                Age = age;
            }

            public string Title { get; }
            public int Age { get; }
        }

        public class ExtraData
        {
            public ExtraData(string company)
            {
                Company = company;
            }

            public string Company { get; }
        }

        public static readonly Dictionary<string, Person> People = new()
        {
            { "A", new Person("Bob", 24) },
            { "B", new Person("Mike", 18) },
            { "C", new Person("Yulia", 21) },
        };

        public static readonly Dictionary<string, ExtraData> PeopleExtraData = new()
        {
            { "A", new ExtraData("Company 1") },
            { "B", new ExtraData("Company 2") },
            { "C", new ExtraData("Company 3") },
        };

        [TestMethod]
        public void MergeTest_with_parse()
        {
            var json = JsonConvert.SerializeObject(People, Formatting.Indented);
            var json2 = JsonConvert.SerializeObject(PeopleExtraData, Formatting.Indented);

            var jObject1 = JObject.Parse(json);
            var jObject2 = JObject.Parse(json2);

            var result = new JObject();
            result.Merge(jObject1);
            result.Merge(jObject2);

            Debug.WriteLine(result);
        }

        [TestMethod]
        public void MergeTest_with_FromObject()
        {
            var jObject1 = JObject.FromObject(People);
            var jObject2 = JObject.FromObject(PeopleExtraData);

            var result = new JObject();
            result.Merge(jObject1);
            result.Merge(jObject2);

            Debug.WriteLine(result);
        }
    }
}

The results should look as follows:

{
    "A": {
        "Title": "Bob",
        "Age": 24,
        "Company": "Company 1"
    },
    "B": {
        "Title": "Mike",
        "Age": 18,
        "Company": "Company 2"
    },
    "C": {
        "Title": "Yulia",
        "Age": 21,
        "Company": "Company 3"
    }
}
GatsbyNetlifyReactTypeScriptTailwind CSS
© Copyright 2008-2022 Terry Butler