Home > Mobile >  JToken get length of array
JToken get length of array

Time:05-31

I have JSON string:

var jsonString = "{ rawRequest: asset: ['123', '456'] }";

And I have mapping param:

var param = "rawRequest.asset.length";

And I need to get count of array items:

JToken token = JToken.Parse(jsonString);
JToken valueToken = token.SelectToken($"$.{param}");
var count = valueToken.Value<int>(); // = 2

but valueToken = null if param = "rawRequest.asset" everything works fine.

How can I get length of array with using JToken? Maybe I need to modify param somehow?

CodePudding user response:

You can cast your JToken to "JArray" and get the items count. Of course, if the path is invalid or does not target an array, the cast will fail.

You can then do the following :

int count = (valueToken as JArray)?.Count ?? -1;

And get -1 if invalid.

CodePudding user response:

Try editing your code like this

var jsonString = "{ rawRequest: ['123', '456'] }";

var param = "rawRequest";

JToken token = JToken.Parse(jsonString);
var valueToken = token.SelectToken(param).Count();

Console.WriteLine(valueToken);
  • Related