我有两个Json文件。一个将是另一个的子集。我必须合并它们。例如,
1.
{
"A": {
"B": {
"C": "D"
}
}
}
2.
{
"A": {
"B": {
"E": "F"
}
}
}
结果json(1 + 2)文件应为
{
"A": {
"B": {
"C": "D"
"E": "F"
}
}
}
我正在使用NewtownSoft从Json文件中读取并尝试反序列化为嵌套字典,但在生成的json文件中未填充值。
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];
}
}
}
这就是我使用嵌套字典的方式,我是从(Nested Dictionary collection in .NET)那里获取的
我通过使用Dictionary而不是NestedDictionary更改了方法。这是合并两个json文件的方法
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);
}
但是生成的json文件为
{
"A": {
"B": {
"C": "D"
},
"B":{
"E": "F"
}
}
}