I have the following JSON object returned from a JSON differ:
{
"lastName": ["Bab", "Beb"],
"middleName": ["Cg", "seeg"],
"contact":
{
"emailAddress": ["[email protected]", "[email protected]"],
"addresses":
[
{
"state": ["AL", "AZ"]
},
{
"state": ["TN", "MO"]
}
]
}
}
I need a list of changes in the following fashion.
lastName/new:Bab/old:Beb
middleName/new:Cg/old:seeg
contact.emailAddress/new:[email protected]/old:[email protected]
contact.addresses[0].state/new:AL/old:AZ
contact.addresses[1].state/new:TN/old:MO
So I wrote this ugly program using a bit of recursion.
private static IEnumerable<DocumentProperty> ParseJObject(JObject node)
{
HashSet<DocumentProperty> documentProperties = new HashSet<DocumentProperty>();
DocumentProperty documentProperty = new DocumentProperty();
foreach (KeyValuePair<string, JToken> sub in node)
{
if (sub.Value.Type == JTokenType.Array)
{
// unnamed nodes which contain nested objects
if (sub.Value.First.Type == JTokenType.Object)
{
foreach (var innerNode in sub.Value.Children())
{
documentProperties.UnionWith(ParseJObject((JObject)innerNode));
}
}
documentProperty = CreateDocumentProperty(sub.Value);
}
else if (sub.Value.Type == JTokenType.Object)
{
documentProperties.UnionWith(ParseJObject((JObject)sub.Value));
}
documentProperties.Add(documentProperty);
}
return documentProperties;
}
It worked except that it is getting me some extra output.
lastName/new:Bab/old:Beb
middleName/new:Cg/old:seeg
contact.emailAddress/new:[email protected]/old:[email protected]
contact.addresses[0].state/new:AL/old:AZ
contact.addresses[1].state/new:TN/old:MO
contact.addresses/new:{ <-----------------------------Extra here.
"state": [
"AL",
"AZ"
]
}/old:{
"state": [
"TN",
"MO"
]
}
I suspect that it is due to how I have my recursion setup. Can you immediately make out what is wrong here?
Definition for CreateDocumentProperty
private static DocumentProperty CreateDocumentProperty(JToken subValue) => new DocumentProperty()
{
PropertyName = subValue.Path,
New = subValue[0].ToString(),
Old = subValue[1].ToString()
};
Main method:
static void Main()
{
JToken jToken = JToken.Parse("{\"lastName\":[\"Bab\",\"Beb\"],\"middleName\":[\"Cg\",\"seeg\"],\"contact\":{\"emailAddress\":[\"[email protected]\",\"[email protected]\"],\"addresses\":[{\"state\":[\"AL\",\"AZ\"]},{\"state\":[\"TN\",\"MO\"]}],}}");
JObject inner = jToken.Value<JObject>();
IEnumerable<DocumentProperty> data = ParseJObject(inner);
foreach (var item in data) Console.WriteLine(item);
}
JsonConvert.DeserializeObject<MyModel>(jsonData).