c# - 将两个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"
}
}
}
解决方案
推荐阅读
- git - RunCloud 部署:您对以下文件 (package-locked.json) 的本地更改将被合并覆盖
- node.js - 使用 Node.js 在 Firebase 中使用 Typescript 进行读写
- python - Python Windows 服务无法生成/写入 CSV
- javascript - 如何判断内联对象标签是否已加载其数据
- elm - 如何将文件加载到 Elm REPL?
- javascript - 如何遍历嵌套对象以检查是否找到 true?
- javascript - TinyMce 4 在初始化后动态添加一个按钮到工具栏
- javascript - 为什么刷新时数据库中只显示一项(Firebase)
- javascript - 设置 CSS 缩放值后,jQuery.position() 在 Chrome 和 Edge 中返回不同的结果
- c - 我是否正确地使用 cURL 模拟 CORS,是否需要实现 OPTIONS 请求