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

huangapple go评论142阅读模式
英文:

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

问题

我有一个看起来像这样的字符串:

[
{
"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
}
]

我该如何获取它的大小/长度?在这种情况下,应该是 2

我不确定是否应该首先解析为 JSONObject/JSONArray?我一直在尝试使用 GSON 库进行解析,但没有成功。

更新

事实证明比我想象的要简单。我甚至不需要使用 GSON:

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

谢谢你的帮助!

英文:

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!

答案1

得分: 2

使用您建议的Gson:

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

MyPojo 是一个表示您的 JSON 的类:

class MyPojo {
    @SerializedName("Slot")
    @Expose
    private Integer slot;
    @SerializedName("Ping")
    @Expose
    private Integer ping;
    // 其他属性
    // 获取器和设置器
}

要从您的 JSON 创建一个 Pojo,您可以查看这个链接

英文:

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.

答案2

得分: 2

如果您只需要大小,则无需任何POJO:

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

您还可以使用List,但因为它是泛型类型,您可能会收到有关原始类型的投诉,也许希望使用类型标记,这会使使用数组更加方便。

英文:

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.

答案3

得分: 1

如果您只想知道JSON数组的长度,您可以使用几乎任何JSON解析器来解析它,然后查看结果对象。在这种情况下,org.json解析器可以胜任。

根据JSON的确切性质,可能可以实现一个巧妙的解决方案,例如计算{字符的数量,或者使用正则表达式更复杂的方法。不建议使用这种方法。问题在于JSON语法(一般情况下)对于这种做法来说过于复杂,不太实际和可靠。您可能会受到边缘情况的困扰,例如嵌套对象或JSON字符串中的{字符。

英文:

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.

答案4

得分: 1

不要将其反序列化为"POJO"或Object[],因为至少有两次建议不要这样做:

  • 这是一种浪费堆内存的方式(如果只需要计算顶级数组元素的数量,为什么要使用对象?);
  • 这是一种牺牲性能的方式(反序列化器执行的工作比"简单"解析器在某种程度上更复杂)。

如果您坚持使用 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;
}

它可以用于_字符串_,如下所示(尽管一般情况下中间的_JSON字符串_不是一个好主意,因为构建这样的字符串会产生成本):

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

或者,如果有文件或网络输入流,可以这样做:

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

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);
}

huangapple
  • 本文由 发表于 2020年8月5日 10:16:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63257483.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定