Hoàng Nguyễn
Hoàng Nguyễn

Reputation: 1170

asp.net - How to get / deserialize object of JsonPatchDocument?

I could serialize the JsonPatchDocument model by using JsonConvert.SerializeObject(), but the type of result is string, how can I convert it to normal array type? Or how to get JsonPatchDocument object straight to array?

var pathSerialized = JsonConvert.SerializeObject(patch);
Console.WriteLine(pathSerialized);

// Result as string: 
// "[{"value":"2018-08-30","path":"/openTo","op":"replace"},{"value":"2018-04-01","path":"/openFrom","op":"replace"}]" 

Upvotes: 4

Views: 7083

Answers (2)

croxy
croxy

Reputation: 4168

You don't have to serialize the JsonPatchDocument object at all. You can access its properties directly through the object. For example filtering for the path property:

var elementsWithPath = patch.Operations.Where(o => o.path.Equals("some path"));

Upvotes: 8

Janilson
Janilson

Reputation: 1193

I think you might be looking to do something with JTokens from the Newtonsoft.Json.Linq namespace. You can turn the pathserialized string into a JToken with var jToken = JToken.Parse(pathSerializer), then explore the underlying objects and properties by enumerating them with var childTokens = jToken.Children().

One of those child tokens is going to be a JObject, which is a Json representation of an object. You can access properties of a JObject with jObject["propertyName"].

Upvotes: 0

Related Questions