GSON 解析器在循环 json 时跳过对象
GSON parser skipping Object while looping over json
我有一个 Json 数组,我将其解析为 GSON。它具有以下内容:
[
{
"type": "way",
"id": 70215497,
"nodes": [
838418570,
838418571
]
},
{
"type": "way",
"id": 70215500,
"nodes": [
838418548,
838418626
]
}
]
我尝试使用以下代码示例对其进行解析:
while (jsonReader.hasNext()){
Element type = gson.fromJson(jsonReader, Element.class);
if (type.GetType().contentEquals("way")) {
Way way = gson.fromJson(jsonReader, Way.class);
System.out.println(way.GetId());
}
}
其中 Element
就是
public class Element {
private String type;
public String GetType() {
return type;
}
}
并且Way
是
public class Way {
private long id;
private String type;
List<Long> nodes;
public long GetId() {
return id;
}
}
现在由于某些原因只有 70215500
会打印出来。这发生在实际代码中的其他一些元素上。这是为什么?
编辑:它基本上只读取 1/2 对象。为什么?
不需要先读Element
class再读Way
class。阅读 Way
并检查其类型:
try (JsonReader jsonReader = new JsonReader(new FileReader(jsonFile))) {
jsonReader.beginArray();
while (jsonReader.hasNext()) {
Way way = gson.fromJson(jsonReader, Way.class);
if (way.getType().contentEquals("way")) {
System.out.println(way.getId());
}
}
}
以上代码应打印所有 id
s.
我有一个 Json 数组,我将其解析为 GSON。它具有以下内容:
[
{
"type": "way",
"id": 70215497,
"nodes": [
838418570,
838418571
]
},
{
"type": "way",
"id": 70215500,
"nodes": [
838418548,
838418626
]
}
]
我尝试使用以下代码示例对其进行解析:
while (jsonReader.hasNext()){
Element type = gson.fromJson(jsonReader, Element.class);
if (type.GetType().contentEquals("way")) {
Way way = gson.fromJson(jsonReader, Way.class);
System.out.println(way.GetId());
}
}
其中 Element
就是
public class Element {
private String type;
public String GetType() {
return type;
}
}
并且Way
是
public class Way {
private long id;
private String type;
List<Long> nodes;
public long GetId() {
return id;
}
}
现在由于某些原因只有 70215500
会打印出来。这发生在实际代码中的其他一些元素上。这是为什么?
编辑:它基本上只读取 1/2 对象。为什么?
不需要先读Element
class再读Way
class。阅读 Way
并检查其类型:
try (JsonReader jsonReader = new JsonReader(new FileReader(jsonFile))) {
jsonReader.beginArray();
while (jsonReader.hasNext()) {
Way way = gson.fromJson(jsonReader, Way.class);
if (way.getType().contentEquals("way")) {
System.out.println(way.getId());
}
}
}
以上代码应打印所有 id
s.