需求项目json作为主模板,会应用到多个子模版,当后续项目变更只需要修改主模板中节点,并且能够动态更新到原来的子模版中去。
主模板示例:
{
"A": {
"A1": "",
"A2": false,
"A3": 1
},
"B": {
"B1": "",
"B2": false,
"B3": 1
},
"C": {
"C1": "",
"C2": false,
"C3": 1
}
}
模板修改后:
{
"A": {
"A1": "",
"A2": true,
"A3": 2,
"A4": "NewValue"
},
"B": {
"B1": "UpdatedValue",
"B2": false,
"B3": 1
},
"C": {
"C1": "",
"C2": false,
"C3": 1
},
"D": {
"D1": "",
"D2": true,
"D3": 3
}
}
UpdateJObject 方法实现可以动态更新json,主模板节点存在则新增,不存在可以变更也可以选择更新数据值。
program:
cs
static void Main(string[] args)
{
string oldJson = "{\"A\":{\"A1\":\"\",\"A2\":false,\"A3\":1},\"B\":{\"B1\":\"\",\"B2\":false,\"B3\":1},\"C\":{\"C1\":\"\",\"C2\":false,\"C3\":1}}";
string newJson = "{\"A\":{\"A1\":\"\",\"A2\":true,\"A3\":2,\"A4\":\"NewValue\"},\"B\":{\"B1\":\"UpdatedValue\",\"B2\":false,\"B3\":1},\"C\":{\"C1\":\"\",\"C2\":false,\"C3\":1},\"D\":{\"D1\":\"\",\"D2\":true,\"D3\":3}}";
JObject oldObject = JObject.Parse(oldJson);
JObject newObject = JObject.Parse(newJson);
Console.WriteLine("更新前:" + oldObject.ToString(Newtonsoft.Json.Formatting.Indented));
// 更新旧JSON对象
UpdateJObject(oldObject, newObject);
Console.WriteLine("存在则更新,不存在新增,更新后:" + oldObject.ToString(Newtonsoft.Json.Formatting.Indented));
oldObject = JObject.Parse(oldJson);
newObject = JObject.Parse(newJson);
// 更新旧JSON对象
UpdateJObject(oldObject, newObject, false);
Console.WriteLine("存在则跳过,不存在新增,更新后:" + oldObject.ToString(Newtonsoft.Json.Formatting.Indented));
}
/// <summary>
/// 更新替换json节点
/// </summary>
/// <param name="target">被更新json</param>
/// <param name="source">源json</param>
/// <param name="isUpdateOriginalData">是否更新目标已存在的节点数据</param>
static void UpdateJObject(JObject target, JObject source, bool isUpdateOriginalData = true)
{
foreach (var child in source)
{
JToken targetChild = target[child.Key];
if (targetChild == null)
{
// 正确添加child到target
target.Add(new JProperty(child.Key, child.Value));
}
else if (child.Value.Type == JTokenType.Object)
{
// 如果child是对象,则递归更新
if (targetChild.Type == JTokenType.Object)
{
UpdateJObject(targetChild as JObject, child.Value as JObject, isUpdateOriginalData);
}
else
{
if (isUpdateOriginalData)
target[child.Key] = child.Value;// 如果targetChild不是对象,则替换整个值
}
}
else
{
if (isUpdateOriginalData)
target[child.Key] = child.Value;// 如果child不是对象,则直接替换值
}
}
}