这是我的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
]
我想要eah数组的前四个值并跳过其余的值,如:
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();
答案 0 :(得分:2)
如果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个值,使用对您的情况有意义的任何方法(例如,首先将它们存储在List中,或者将它们存储为字符串然后再解析,或者任何你想要的东西 - 重点是,不要对数组中的元素数量做出假设,坚持规则并在读取每个元素之前使用hasNext())。