2

I'm using "Newtonsoft.Json.Linq.JObject" in my application.

I have a method that receives a JObject in the format:

{
  "PersonnelIds": "[31,32,33,34]"
}

And I want to parse the content of PersonnelIds to a List of Integers.

What is the best way of doing that?

Pedro Vaz
  • 820
  • 5
  • 11

2 Answers2

9

I can see that the values of the PersonnelIds is written as string "[31,32,33,34]" so to parse it with this syntax you can use the following code

JObject jObject = JObject.Parse(myjson);
JToken jToken = jObject.GetValue("PersonnelIds");
var array = JArray.Parse(jToken.Value<string>()).Select(x => (int)x).ToArray();

if your value is not string so your JSON is like {"PersonnelIds": [31,32,33,34] } then you can parse it using the following code

JObject jObject = JObject.Parse(myjson);
JToken jToken = jObject.GetValue("PersonnelIds");
int[] array = jToken.Values<int>().ToArray();
Hossam Barakat
  • 1,399
  • 9
  • 19
0

Create a class to deserialize your json:

To create classes, you can copy the json in clipboard and use the

Edit / Paste special / Paste JSON as class

in visual studio (I use vs2013).

Then deserialize your string.

See my solution on this post

Community
  • 1
  • 1
Eric Bole-Feysot
  • 13,949
  • 7
  • 47
  • 53