1

I have a String which looks like this

 [
  {
    "Slot": 1,
    "Ping": 40,
    "Kills": 0,
    "Deaths": 0,
    "Score": 0,
    "Team": "Reb",
    "Name": "ascasdasd",
    "KeyHash": "",
    "IsBanned": false,
    "TotalVisits": 34,
    "GroupName": "",
    "RemoteAddressStr": "",
    "DatabaseId": 1412
  },
  {
    "Slot": 3,
    "Ping": 116,
    "Kills": 0,
    "Deaths": 0,
    "Score": 0,
    "Team": "Reb",
    "Name": "",
    "KeyHash": "",
    "IsBanned": false,
    "TotalVisits": 1,
    "GroupName": "",
    "RemoteAddressStr": "",
    "DatabaseId": 8226
  }
]

How can I get the size/length of it? In this case it should be 2

I'm not sure if I should parse it to JSONObject/JSONArray first? I've been trying to parse it using GSON Library with no success.

Update

Turns out it was simpler than I thought. I didn't even needed GSON:

int sizeOfJSONArrayString = new JSONArray(jsonString).length();

Thank you for your help!

  • Have a look at https://stackoverflow.com/questions/18977144/how-to-parse-json-array-not-json-object-in-android. What you jave should be parse into a JSONArray, and then fetch JSONObjects from the array. – Kasalwe Aug 05 '20 at 02:19

4 Answers4

2

Using Gson as you suggested:

Gson gson = new Gson();
MyPojo[] myPojoArray = gson.fromJson(json, MyPojo[].class); 
System.out.println(myPojoArray.length); // prints 2

MyPojo is a class that represents your json:

class MyPojo {
    @SerializedName("Slot")
    @Expose
    private Integer slot;
    @SerializedName("Ping")
    @Expose
    private Integer ping;
    // other properties
    // getters and setters
}

To create a Pojo from your JSON you can check this.

Marc
  • 2,738
  • 1
  • 17
  • 21
2

There is no need for any POJO if you need only the size:

int length = new Gson().fromJson(JSON, Object[].class).length;

You could also use List but because it is generic type you would get complaints about raw type and maybe wanted to use type token which makes using array more convenient.

pirho
  • 11,565
  • 12
  • 43
  • 70
1

If you just want to know the length of the JSON array, you can parse it with just about any JSON parser, and then look at the result object. In this case the org.json parser would do fine.

Depending on the exact nature of the JSON, it might be possible to implement a hacky solution that (say) counts the number of { characters, or something a bit more sophisticated using regexes. This approach is not recommended. The problem is JSON syntax (in general) is too complicated for that to be practical and reliable. You are liable to be tripped up by edge cases; e.g. a nested object or a { character in a JSON string.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

Don't deserialize to "POJO"s or Object[] as it was suggested at least twice:

  • it's a way to waste the heap (why have objects if you only need to count the number of the top array elements?);
  • and it's a way to sacrifice performance (deserializers do a more complex job than "simple" parsers do to some extent).

If you're stuck to Gson, it might be implemented in Gson like this:

public static int getTopElementCount(final JsonReader jsonReader)
        throws IOException {
    jsonReader.beginArray();
    int length = 0;
    for ( ; jsonReader.hasNext(); length++ ) {
            jsonReader.skipValue();
    }
    jsonReader.endArray();
    return length;
}

And it can be used for strings like this (despite intermediate JSON strings are a bad idea in general because of the cost to build such a string):

final int length = JsonUtils.getTopElementCount(new JsonReader(new StringReader(json)));

Or, if there's a file or a network input stream, then:

try ( final JsonReader jsonReader = new JsonReader(new InputStreamReader(new FileInputStream(...), StandardCharsets.UTF_8)) ) {
    final int length = JsonUtils.getTopElementCount(jsonReader);
}