gpt4 book ai didi

java - 循环没有中断 - 使用 GSON 解析 JSON

转载 作者:行者123 更新时间:2023-11-30 04:17:21 27 4
gpt4 key购买 nike

这是我的 JSON 数组:

[
[ 36,
100,
"The 3n + 1 problem",
56717,
0,
1000000000,
0,
6316,
0,
0,
88834,
0,
45930,
0,
46527,
5209,
200860,
3597,
149256,
3000,
1
],
[
........
],
[
........
],
.....// and almost 5000 arrays like above
]

我想要每个数组的前四个值并跳过其余的值,例如:

36 100 "The 3n + 1 problem" 56717

这是我到目前为止编写的代码:

reader.beginArray();
while (reader.hasNext()) {
reader.beginArray();
while (reader.hasNext()) {
System.out.println(reader.nextInt() + " " + reader.nextInt()
+ " " + reader.nextString() + " "
+ reader.nextInt());
for (int i = 0; i < 17; i++) {
reader.skipValue();
}
reader.skipValue();
}
reader.endArray();
System.out.println("loop is break"); // this is not printed as the inner loop is not breaking
}
reader.endArray();
reader.close();

它正在按我的预期打印:

36 100 "The 3n + 1 problem" 56717
.................................
..................................
1049 10108 The Mosquito Killer Mosquitos 49
1050 10109 Solving Systems of Linear Equations 129
1051 10110 Light, more light 9414
1052 10111 Find the Winning Move 365

这是有效的,但内部循环没有正确中断。我的代码有什么问题吗?我在那里错过了什么,导致我的代码无法正常工作?

编辑:(解决方案)我最终得到了这个解决方案:

reader.beginArray();
while (reader.hasNext()) {
reader.beginArray();
// read and parse first four elements, checking hasNext() each time for robustness
int a = reader.nextInt();
int b = reader.nextInt();
String c = reader.nextString();
int d = reader.nextInt();
System.out.println(a + " " + b + " " + c + " " + d);
while (reader.hasNext())
reader.skipValue();
reader.endArray();
}
reader.endArray();

最佳答案

如果 hasNext() 返回 false,则您不想调用skipValue() 或next*。 GSON documentation建议先积累数值。该主题的一个变体是:

reader.beginArray();
while (reader.hasNext()) {
int position;
int a, b, d; // stores your parsed values
String c; // stores your parsed values
reader.beginArray();
// read and parse first four elements, checking hasNext() each time for robustness
for (position = 0; position < 4 && reader.hasNext(); ++ position) {
if (position == 0) a = reader.nextInt();
else if (position == 1) b = reader.nextInt();
else if (position == 2) c = reader.nextString();
else if (position == 3) d = reader.nextInt();
}
// if position < 4 then there weren't enough values in array.
if (position == 4) { // correctly read
System.out.println(a + " " + b + " " + c + " " + d);
}
// skip rest of array, regardless of number of values
while (reader.hasNext())
reader.skipValue();
reader.endArray();
}
reader.endArray();

请注意,还有很多其他方法可以解析前 4 个值,可以使用任何适合您情况的方法(例如,首先将它们存储在列表中,或者将它们存储为字符串,然后稍后解析,或者您想要的任何方法 -要点是,不要假设数组中元素的数量,遵守规则并在读取每个元素之前使用 hasNext()。

关于java - 循环没有中断 - 使用 GSON 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18045753/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com