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"}]" 
7
  • 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? Commented Jun 13, 2018 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? Commented Jun 13, 2018 at 12:54
  • 1
    Why serializing it then in the first place? Why not just accessing the properties of JsonPatchDocument? Commented Jun 13, 2018 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. Commented Jun 13, 2018 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? Commented Jun 13, 2018 at 13:08

2 Answers 2

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"));
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.