aspnet / JsonPatch

[Archived] JSON PATCH library. Project moved to https://github.com/aspnet/AspNetCore
Apache License 2.0
103 stars 48 forks source link

Failed to apply patch on json as string #75

Closed bhatnagar-anuj closed 7 years ago

bhatnagar-anuj commented 7 years ago

I'm trying to apply patch on the JSON feeds as string nad getting error Unable to cast object of type 'Newtonsoft.Json.Serialization.JsonPrimitiveContract' to type 'Newtonsoft.Json.Serialization.JsonObjectContract'. Code sample.

var patch = new JsonPatchDocument(); patch.Replace("/region", "test"); patch.ApplyTo("{\"region\": \"amer\", \"foo1\": {\"foo11\": \"val1\", \"foo12\": 2}}");

I tried using latest version "Microsoft.AspNetCore.JsonPatch" it's failing with the different error. "The target location specified by path segment 'region' was not found."

Eilon commented 7 years ago

@jbagga - can you investigate what's going on here?

jbagga commented 7 years ago

@bhatnagar-anuj To use Replace, you either need a C# object to convert the JObject into or convert it to an ExpandoObject as follows:

var converter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>("{ \"region\": \"amer\", \"foo1\": { \"foo11\": \"val1\", \"foo12\": 2}}");
patch.ApplyTo(obj);

You cannot perform this operation on a string.

cc @kichalla