2

I have a JSON string below:

{
  "data": [
    {
      //data for first
    }, 
    {
      //data for second
    }, 
    {
      //data for third
    }, 
  ]
}

From this JSON string, I would like to retrieve the number of objects within the "data" element, which in this case, would be 3.

What would be the best approach to accomplish this? I used the .Length property, but that returned a number that I did not expect.

I am using C#.

  • I'm currently reading the JSON into a string, but I am looking into using a JSON parser. Do you have any suggestions? –  Jan 05 '12 at 17:01
  • 1
    I highly recommend Json.NET (see http://james.newtonking.com/pages/json-net.aspx). Also see my answer below for an example usage. – Phil Klein Jan 05 '12 at 17:08
  • 1
    `.Length` will give you the number of charachter in the `String`. To find the objects you will need to deserialise the JSON using `JavaScriptSerializer` or `DataContractJsonSerializer`, both of which will require a compatible type. Alternatively you could use one of many third party assemblies or, roll your own deserialiser (not reccomended) or finally you could count the number of braces, accounting for opening, closing and nesting and deduce the count that way. – Jodrell Jan 05 '12 at 17:19

3 Answers3

3

Since it's a string in C# you need to parse it into something you can use first. Here's a simple way using framework classes.

//obj is your JSON string

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Dictionary<string,object> csObj = 
    serializer.Deserialize<Dictionary<string,object>>(obj);
int length = ((ArrayList)csObj["data"]).Count; 

When given a generic data structure, JavaScriptSerializer turns arrays into ArrayLists.

Jamie Treworgy
  • 23,934
  • 8
  • 76
  • 119
1

Here's an example using Newtonsoft.Json (Json.NET) which is available as a NuGet package.

Usage:

var jsonString = @"{
    ""data"": [
        {
            Name: ""Mike"", Age: 30
        }, 
        {
            Name: ""John"", Age: 42
        }, 
        {
            Name: ""Tom"", Age: 44
        }
    ]
}";

var example = JsonConvert.DeserializeObject<Example>(jsonString);
// example.Data.Length == 3 at this point

Classes

class Example
{
    public Person[] Data { get; set; }
}

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
Phil Klein
  • 7,344
  • 3
  • 30
  • 33
0

You need to first deserialize your json string to get objects. The below post has a couple examples. After you deserialize you should have a collection of your data objects in c# (not a string). From there you should be able to call collection.Count or array.Length depending on what collection type you are using.

C# automatic property deserialization of JSON

Community
  • 1
  • 1
Kenneth Ito
  • 5,201
  • 2
  • 25
  • 44