Created
August 13, 2019 18:07
-
-
Save gordonglas/6c9ddff073291f8aa90b842caad97154 to your computer and use it in GitHub Desktop.
JSON.NET - Merge Json #json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Newtonsoft.Json; | |
using Newtonsoft.Json.Linq; | |
namespace CommonLib | |
{ | |
public class JsonHelper | |
{ | |
/* | |
string json = JsonHelper.MergeJson(null, @"{ | |
'FirstName': 'John', | |
'LastName': 'Smith', | |
'Enabled': false, | |
'Roles': [ 'User' ] | |
}", "User"); | |
string mergedJson = JsonHelper.MergeJson(json, @"{ | |
'Foo': 'Bar', | |
'Count': 42, | |
'Success': true, | |
}", "Misc", Formatting.Indented); | |
...returns: | |
{ | |
"User": { | |
"FirstName": "John", | |
"LastName": "Smith", | |
"Enabled": false, | |
"Roles": [ | |
"User" | |
] | |
}, | |
"Misc": { | |
"Foo": "Bar", | |
"Count": 42, | |
"Success": true | |
} | |
} | |
*/ | |
public static string MergeJson(string origJson, string newJson, | |
string newJsonRootKey, Formatting formatting = Formatting.None) | |
{ | |
JObject newObj = JObject.Parse(newJson); | |
if (newJsonRootKey != null) | |
{ | |
// wrap new object in the specified root key | |
newObj = new JObject | |
{ | |
[newJsonRootKey] = newObj, | |
}; | |
} | |
if (origJson == null) | |
{ | |
return newObj.ToString(formatting); | |
} | |
else | |
{ | |
// merge | |
JObject oldObj = JObject.Parse(origJson); | |
oldObj.Merge(newObj, new JsonMergeSettings | |
{ | |
MergeArrayHandling = MergeArrayHandling.Replace, | |
MergeNullValueHandling = MergeNullValueHandling.Merge, | |
}); | |
return oldObj.ToString(formatting); | |
} | |
} | |
// https://www.newtonsoft.com/json/help/html/SelectToken.htm | |
// https://www.newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm | |
// string firstName = JsonHelper.GetJObjectProperty<string>(jObject, "$.User.FirstName"); | |
// int? count = JsonHelper.GetJObjectProperty<int?>(jObject, "$.Misc.Count"); | |
public static T GetJObjectProperty<T>(JObject obj, string jpathExpression) | |
{ | |
JToken jToken = obj.SelectToken(jpathExpression); | |
if (jToken == null) | |
return default(T); | |
T t = jToken.ToObject<T>(); | |
return t; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment