简体   繁体   English

如何从 JSON 字符串中获取数组的大小?

[英]How to get the size of an array from a JSON string?

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在这种情况下,它应该是2

I'm not sure if I should parse it to JSONObject/JSONArray first?我不确定是否应该先将其解析为 JSONObject/JSONArray? I've been trying to parse it using GSON Library with no success.我一直在尝试使用 GSON 库来解析它,但没有成功。

Update更新

Turns out it was simpler than I thought.事实证明它比我想象的要简单。 I didn't even needed GSON:我什至不需要 GSON:

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

Thank you for your help!谢谢您的帮助!

Using Gson as you suggested:按照您的建议使用 Gson :

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: MyPojo是一个 class 代表您的 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 .要从您的 JSON 创建一个 Pojo,您可以检查这个

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.如果您只想知道 JSON 数组的长度,您可以使用几乎任何 JSON 解析器对其进行解析,然后查看结果 object。 In this case the org.json parser would do fine.在这种情况下,org.json 解析器就可以了。

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.根据 JSON 的确切性质,有可能实现一个 hacky 解决方案,(比如)计算{字符的数量,或者使用正则表达式更复杂的东西。 This approach is not recommended.不推荐这种方法。 The problem is JSON syntax (in general) is too complicated for that to be practical and reliable.问题是 JSON 语法(通常)太复杂以至于不实用和可靠。 You are liable to be tripped up by edge cases;你很容易被边缘情况绊倒; eg a nested object or a { character in a JSON string.例如嵌套的 object 或 JSON 字符串中的{字符。

There is no need for any POJO if you need only the size:如果您只需要大小,则不需要任何 POJO:

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.您也可以使用List ,但因为它是泛型类型,您会收到有关原始类型的抱怨,并且可能想要使用类型标记,这使得使用数组更方便。

Don't deserialize to "POJO"s or Object[] as it was suggested at least twice:不要反序列化为“POJO”或Object[] ,因为它被建议至少两次:

  • 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:如果您坚持使用 Gson,它可能会在 Gson 中实现,如下所示:

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):它可以用于这样的字符串(尽管中间JSON 字符串通常是一个坏主意,因为构建这样一个字符串的成本很高):

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

Or, if there's a file or a network input stream, then:或者,如果有文件或者网络输入stream,那么:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM