skip to Main Content

I want to merge my JSONs into one while dominant one overwriting values.

Example:

Subordinate JSON:

{
    "test": {
        "test1": true,
        "test2": {
            "test3": [1, 2, 3]
        }
    }
}

Dominating JSON:

{
    "test": {
        "test2": null,
        "test3": "string"
    },
    "test2": "newValue"
}

Merge result:

{
    "test": {
        "test1": true,
        "test2": null,
        "test3": "string"
    },
    "test2": "newValue"
}

With which command can I do it easily?

2

Answers


  1. Chosen as BEST ANSWER

    Thanks @Ariel Szmerla for giving answer, but look's like its kindly obsolete. For C#10 and Newtonsoft.Json v13.0.3 i used this code:

            JObject sub = JObject.Parse(@"{ ""test"": { ""test1"": true, ""test2"":  15, ""test3"": { ""test4"": [1, 2, 3] } } }");
    
            JObject dom = JObject.Parse(@"{ ""test"": { ""test2"": 16, ""test3"": ""string"" }, ""test5"": ""newValue"" }");
    
            JObject merged;
            {
                merged = (JObject)sub.DeepClone();
                merged.Merge(dom, new JsonMergeSettings() {MergeNullValueHandling = MergeNullValueHandling.Merge, MergeArrayHandling = MergeArrayHandling.Replace});
            }
            
            return merged.ToObject<T>();
    

  2. I use the Newtonsoft.Json lib.

    You can use the JObject.Merge method to combine two JSON objects into one, and specify how to handle the values that are not present in both objects.

    Here is a sample code that shows how to do son:

    using Newtonsoft.Json.Linq;
    
    JObject sub = JObject.Parse(@"{ ““test””: { "“test1"”: true, "“test2"”: { ““test3"”: [1, 2, 3] } } }”);
    
    JObject dom = JObject.Parse(@"{ ““test””: { "“test2"”: null, "“test3"”: ““string”” }, ““test2"”: ““newValue”” }”);
    
    // Merge the two JSONs using Merge method 
    JObject merged = dom.Merge(sub, new JsonMergeSettings() {  = MergeArrayHandling.Keep, ReplaceNullValuesWith = null });
    
    // Convert the result to string for visualization:
    string result = JsonConvert.SerializeObject(merged);
    
    // Print the result Console.WriteLine(result);
    // output:
    // { “test”: { “test1”: true, “test2”: null, “test3”: “string” }, “test2”: “newValue” }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search