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"
]
}
}
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
tokenParcialreplace the property values oftokenOrigenyou can do so easily with LINQ:As required, this results in:
Demo fiddle here.