4

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"}]" 
Hoàng Nguyễn
  • 1,121
  • 3
  • 33
  • 57
  • 3
    uhm ... that is the purpose of `SerializeObject` ... it provides you with a string representation of whatever you feed it. If you want those json-objects in a separate array, you have to serialize them each on their own or did i miss something? – X39 Jun 13 '18 at 12:49
  • I want to check condition of properties of that object, then string type is impossible to check it, that's why I wanted to get the object. Do you have any solution? – Hoàng Nguyễn Jun 13 '18 at 12:54
  • 1
    Why serializing it then in the first place? Why not just accessing the properties of `JsonPatchDocument`? – croxy Jun 13 '18 at 13:01
  • Yeah, I'm confused as well. You're starting with a full-fledged strongly-typed object, converting it to a JSON string, and then complaining that you don't want it to be a JSON string. Then, don't convert it to a JSON string. – Chris Pratt Jun 13 '18 at 13:08
  • @croxy I tried to access properties directly, but then it returned error like `JsonPatchDocument does not contain definition of 'path'`. Do you have suggestions? – Hoàng Nguyễn Jun 13 '18 at 13:08
  • Because it *doesn't*. Based on the serialized string, `patch` is actually a collection type, meaning you'd need to do something like `patch[0].path`, i.e. get an item from the collection *first* and then access the `path` property off that. – Chris Pratt Jun 13 '18 at 13:10
  • Yea, i'm noob, my classmate told me that I had to serialize it first, but this would not go to anywhere, then I just made question here. – Hoàng Nguyễn Jun 13 '18 at 13:17

2 Answers2

8

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"));
croxy
  • 4,082
  • 9
  • 28
  • 46
0

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"].

Janilson
  • 1,042
  • 1
  • 9
  • 23