是否有任何方法可以识别在合并中所做的更改?例如,这是两个JSON文件test1.json
{
f1: "String",
f2: true,
f3: 1000001,
f4: [1]
}
。和test2.json
{
f1: "String",
f2: 1,
f3: 1000002,
f4: [1,2]
}
第一个f2
是一个布尔值,第二个f2
是一个数字。同样,f3
的值也会更改,并且会向f4
添加一个额外的项目。
有什么办法记录这些变化?我最感兴趣的是数据类型的更改,而不是内容的更改。
答案 0 :(得分:1)
您可以读取两个JSON文件,将它们都反序列化为Dictionary<string,object>
,然后将它们与String.Equals()
进行比较并输出差异。
下面的演示假设问题中显示的是一层深度的JSON结构。深度嵌套的JSON对象应采用相同的逻辑,但是遍历JSON对象和匹配键的方式将发生变化。对于具有不同深度的更深层次的JSON对象,将需要使用递归遍历。
基本演示:
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MergeJson {
public static class Program {
private static string FILE_ONE = "test1.json";
private static string FILE_TWO = "test2.json";
/// <summary>
/// Converts JSON file into Dictionary
/// </summary>
/// <param name="path">The path of the JSON file</param>
/// <returns>The converted Dictionary</returns>
private static Dictionary<string, object> GetJsonDict (string path) {
// Read json file into string
string json = File.ReadAllText (path);
// Deserialize JSON string into dictionary
var jsonDict = JsonConvert.DeserializeObject<Dictionary<string, object>> (json);
return jsonDict;
}
public static void Main (string[] args) {
// Get both Dictionaries
var jsonDictOne = GetJsonDict (FILE_ONE);
var jsonDictTwo = GetJsonDict (FILE_TWO);
// Go through each key in the first dictionary and compare with second dictionary
foreach (KeyValuePair<string, object> entry in jsonDictOne) {
// Get key and value
var value = entry.Value;
var key = entry.Key;
// Ensure second dictionary has key
if (jsonDictTwo.ContainsKey (key)) {
var otherValue = jsonDictTwo[key];
// Compare both values and output differences
if (!value.Equals (otherValue)) {
FormattableString difference = $"Difference in key {entry.Key}: {value} -> {otherValue}";
Console.WriteLine (difference);
}
}
}
}
}
}
输出:
Difference in key f2: True -> 1
Difference in key f3: 1000001 -> 1000002
Difference in key f4: [
1
] -> [
1,
2
]