1

So, I am trying to count the amount of values in JSON using c#. The Json is:

{
  "Someid": 657442,
  "roles": [
    {
      "id": 3892751,
      "name": "Guest",
      "rank": 0,
      "memberCount": 0
    },
    {
      "id": 3892750,
      "name": "Fanz!<3",
      "rank": 1,
      "memberCount": 0
    },
    {
      "id": 3892749,
      "name": "Lead-Singer",
      "rank": 254,
      "memberCount": 0
    },
    {
      "id": 3892748,
      "name": "Drums",
      "rank": 255,
      "memberCount": 0
    }
  ]
}

I want to count the amount "roles". The JSON is just in a string variable. Help?

3
  • 1
    Deserialize it into an array, then get Length? Commented Sep 10, 2019 at 12:38
  • 1
    Deserialize it to the appropriate data structure, and read obj.Roles.Length? Commented Sep 10, 2019 at 12:38
  • I'd suggest starting with app.quicktype.io?share=IEs9emLGOZgseqkyggdt . Commented Sep 10, 2019 at 12:45

1 Answer 1

6

You can either use like this:

var token = JToken.Parse(input);
var roles= token.Value<JArray>("roles");
var count = roles.Count;

Or you can also use JsonPath:

var token = JToken.Parse(input);
var count = token.SelectTokens("$.roles[*]").Count();

But ideally, you should be serilizing into an object and then using the properties to get the Count:

public class Role
{
    public int id { get; set; }
    public string name { get; set; }
    public int rank { get; set; }
    public int memberCount { get; set; }
}

public class MyObject
{
    public int Someid { get; set; }
    public List<Role> roles { get; set; }
}

var item = JsonConvert.DeserializeObject<MyObject>(input);
var count = item.roles.Count;
Sign up to request clarification or add additional context in comments.

2 Comments

I get the following error: Object reference not set to an instance of an object.
With which example? And which line?

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.