Is there a library (C# preferred) to resolve what I would call multi-level cascading JSON?
Here is an example of what I mean: (Pseudocode/C#)
<Not that I know of. For the simple case, you can use any JSON library, then merge the dictionaries with a solution like this one. E.g. using Newtonsoft/Json.NET:
Dictionary<String, String> dict1, dict2, dict3, merged;
dict1 = JsonConvert.DeserializeObject<Dictionary<string,string>>(json1);
dict2 = JsonConvert.DeserializeObject<Dictionary<string,string>>(json2);
dict3 = JsonConvert.DeserializeObject<Dictionary<string,string>>(json3);
merged = Merge(new[]{dict1, dict2, dict3});
Obviously, in production code you'd factor out the redundant lines.
This is super easy using the excellent JSON.NET library. This method combines objects with properties that are are strings, numbers, or objects.
public static string Cascade(params string[] jsonArray)
{
JObject result = new JObject();
foreach (string json in jsonArray)
{
JObject parsed = JObject.Parse(json);
foreach (var property in parsed)
result[property.Key] = property.Value;
}
return result.ToString();
}
Result, given your example:
{
"firstName": "Albert",
"lastName": "Smith",
"phone": "12345"
}
By adjusting this solution to work recursively, you can merge child objects. The following example will match your expected results (except for the array). You will be able to easily extend this solution to merge arrays (JArray
) in a manner similar to how it merges objects (JObject
).
public static string Cascade(params string[] jsonArray)
{
JObject result = new JObject();
foreach (string json in jsonArray)
{
JObject parsed = JObject.Parse(json);
Merge(result, parsed);
}
return result.ToString();
}
private static void Merge(JObject receiver, JObject donor)
{
foreach (var property in donor)
{
JObject receiverValue = receiver[property.Key] as JObject;
JObject donorValue = property.Value as JObject;
if (receiverValue != null && donorValue != null)
Merge(receiverValue, donorValue);
else
receiver[property.Key] = property.Value;
}
}