首页 > 解决方案 > 将两个json文件合并为一个

问题描述

我有两个 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];
            }
        }
    }

这就是我使用嵌套字典的方式,我取自(.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"   
    }
  }
}

标签: c#json

解决方案


推荐阅读