Empty Object don't override in Merge using JSON.net

46 Views Asked by At

I have this code, for merge 2 json (complete and partial). There is a empty object.

string jsonOrigen = @"
 {
     'business': {
         'tradingaccount': [
             '60325f59-6bef-418a-69a1-08db40bce9af',
             '054ae632-9b82-4644-6e8c-08db45721efd'
         ],
         'campaign': [
             'cf308053-3118-4e92-7bb7-08db73cba4df',
             '5ad21da9-337a-4afc-7bb8-08db73cba4df'
         ],
         'service': [
             'ab14b586-38d8-41a2-01d4-08db86a59448',
             'adac9392-d602-4874-01d5-08db86a59448'
         ]
     }
 }";

 string jsonParcial = @"{ 'business': {} }";

 JObject tokenOrigen = JObject.Parse(jsonOrigen);
 JObject tokenParcial = JObject.Parse(jsonParcial);

 tokenOrigen.Merge(tokenParcial, new JsonMergeSettings
 {
     MergeNullValueHandling = MergeNullValueHandling.Merge
 });

 string res = tokenOrigen.ToString(Formatting.Indented);

The output should be

    "business": {}

but is

 {
  "business": {
    "tradingaccount": [
      "60325f59-6bef-418a-69a1-08db40bce9af",
      "054ae632-9b82-4644-6e8c-08db45721efd"
    ],
    "campaign": [
      "cf308053-3118-4e92-7bb7-08db73cba4df",
      "5ad21da9-337a-4afc-7bb8-08db73cba4df"
    ],
    "service": [
      "ab14b586-38d8-41a2-01d4-08db86a59448",
      "adac9392-d602-4874-01d5-08db86a59448"
    ]
  }
}
1

There are 1 best solutions below

0
dbc On

JContainer.Merge() is designed to do a deep merge where the values of properties with identical names are recursively merged. Since the empty "business" object has no properties, it has nothing to merge in and the original "business" object is unchanged.

If you want a shallow merge where the properties values of tokenParcial replace the property values of tokenOrigen you can do so easily with LINQ:

var query = tokenParcial.Properties().Concat(tokenOrigen.Properties())
    .GroupBy(p => p.Name)
    .Select(p => p.First()); // First() takes the properties of tokenParcial before those of tokenOrigen
var merged = new JObject(query);

string res = merged.ToString(Formatting.Indented);

As required, this results in:

{
  "business": {}
}

Demo fiddle here.