通过JSONPath在指定位置添加JSON

时间:2016-03-07 09:21:07

标签: c# json.net jsonpath

我从用户那里获得了JSON和JSONPath。用户还向我提供了他想要添加到他的JSON中的新内容(值或对象)。我正在尝试创建一个方法,将新内容添加到JSONPath指定的路径。

方法输入:json,jsonpath,newcontent(string) 方法输出:添加了newcontent的新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
      }
    ]
  }
}

JSONPath示例

$.store

要添加的对象

movie [title : The Godfather]

方法返回

{ "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"
      }
    ]
  }
}

1 个答案:

答案 0 :(得分:1)

您可以这样做:

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();
}