I have two Json file. One will be subset of the other. I have to merge them. For example,
1.
{
"A": {
"B": {
"C": "D"
}
}
}
2.
{
"A": {
"B": {
"E": "F"
}
}
}
resultant json (1 + 2) file should be
{
"A": {
"B": {
"C": "D"
"E": "F"
}
}
}
I am using NewtownSoft to read from Json file and tried to deserialize into nested dictionary but value is not populating on the resultant json file.
public class NestedDictionary<K, V> : Dictionary<K, NestedDictionary<K, V>>
{
public V Value { set; get; }
public new NestedDictionary<K, V> this[K key]
{
set { base[key] = value; }
get
{
if (!base.Keys.Contains<K>(key))
{
base[key] = new NestedDictionary<K, V>();
}
return base[key];
}
}
}
This is how I am using nested dictionary, I took it from (Nested Dictionary collection in .NET)
I changed my approach by using Dictionary instead of NestedDictionary. Here is the method which is merging the two json files
public static void MergeJsonFile()
{
string[] json2 = parent.ToArray();
Dictionary<string,object> json2Data = (Dictionary<string, object>) parents.Reverse().Aggregate((object)null, (a, s) => a == null ? (object)s : new Dictionary<string, object> { { s, a } });
string json = JsonConvert.SerializeObject(json2Data, Formatting.Indented);
string json1 = System.IO.File.ReadAllText(@"C:\Users\Desktop\changes.json");
Dictionary<string, object> existingChangedDataDictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(savedChangedData);
Dictionary<string, object> temp = existingChangedDataDictionary, prevDictionary = null;
int x = 0;
List<string> keys = new List<string>(existingChangedDataDictionary.Keys);
while (keys.Contains(parents[x]))
{
prevDictionary = temp;
temp = JsonConvert.DeserializeObject<Dictionary<string, object>>(temp[parents[x]].ToString());
json2Data = (Dictionary<string, object>)json2Data[parents[x]];
keys = new List<string>(temp.Keys);
x++;
}
var updatedData = JsonConvert.SerializeObject(existingChangedDataDictionary, Formatting.Indented);
System.IO.File.WriteAllText(@"C:\Users\Desktop\changes.json",updatedData);
}
But the resultant json file comes as
{
"A": {
"B": {
"C": "D"
},
"B":{
"E": "F"
}
}
}