通过JSON路径在指定位置添加JSON

Adding JSON in the specified place by JSONPath

我从用户那里得到 JSON 和 JSON路径。用户还给我一个他想添加到他的 JSON 的新内容(值或对象)。我正在尝试创建一种方法,它将新内容添加到 JSONPath.

指定的路径中

方法输入:json,jsonpath,newcontent(string) 方法输出:新 json 添加了新内容

JSON 例子

{ "store": {
    "book": [ 
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      }
    ]
  }
}

JSON路径示例

$.store

要添加的对象

movie [title : The Godfather]

方法returns

{ "store": {
    "book": [ 
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      }
    ],
    "movie": [
      {
        "title" : "The Godfather"
      }
    ]
  }
}

你可以这样做:

string ApplyChange(string originalJson, string path, string jsonToAdd)
{
    var root = JObject.Parse(originalJson);
    var node = root.SelectToken(path);
    switch (node.Type)
    {
        case JTokenType.Object:
        {
            var objectToMerge = JObject.Parse("{" + jsonToAdd + "}");
            ((JObject)node).Merge(objectToMerge);
            break;
        }
        case JTokenType.Array:
        {
            var objectToMerge = new JArray(JToken.Parse(jsonToAdd));
            ((JArray)node).Merge(objectToMerge);
            break;
        }
        default:
            throw new NotSupportedException();
    }
    return root.ToString();
}