我有一个json
看起来像这样的文件
{
"races": [
{
"name" : "ORC"
},
{
"name" : "HUMAN"
},
{
"name" : "ELF"
}
],
"npc": [
{
"race" : "HUMAN",
"age" : "25",
"name" : "Jerome"
},
{
"race" : "ORC",
"age" : "26",
"name" : "Rz'Ul"
}
]
}
我想根据需要races
或npc
单独检索数据。我genson
用来解析JSON
. 我这样解析
@SuppressWarnings("unchecked")
public static <T> List<T> readJsonList(String listName) {
Genson genson = JsonContext.PARSER.getParser();
List<T> result = null;
try (InputStream is = JsonDataProcessor.class.getResourceAsStream(FILE)) {
ObjectReader reader = genson.createReader(is);
reader.beginObject();
while (reader.hasNext()) {
reader.next();
if ("races".equals(listName) && "races".equals(reader.name())) {
result = (List<T>) processRaceData(reader);
break;
}
if ("npc".equals(listName) && "npc".equals(reader.name())) {
result = (List<T>) processNpcData(reader);
break;
}
}
reader.endObject();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
例如解析的方法races
看起来像这样
private static List<Race> processRaceData(ObjectReader reader) {
List<Race> raceList = new ArrayList<>();
reader.beginArray();
while (reader.hasNext()) {
reader.next();
Race race = new Race();
reader.beginObject();
while (reader.hasNext()) {
reader.next();
if ("name".equals(reader.name())) { race.setName(reader.valueAsString()); }
else { reader.skipValue(); }
}
reader.endObject();
raceList.add(race);
}
reader.endArray();
return raceList;
}
在调试它populates
变量result
就好了,但endObject
在线我得到异常
Exception in thread "main" com.owlike.genson.stream.JsonStreamException: Illegal character at row 11 and column 4 expected } but read ',' !
at com.owlike.genson.stream.JsonReader.newWrongTokenException(JsonReader.java:942)
at com.owlike.genson.stream.JsonReader.end(JsonReader.java:428)
at com.owlike.genson.stream.JsonReader.endObject(JsonReader.java:177)
at com.lapots.breed.platform.json.JsonDataProcessor.readJsonList(JsonDataProcessor.java:41)
at com.lapots.breed.platform.Example.prepareDb(Example.java:18)
at com.lapots.breed.platform.Example.main(Example.java:23)
问题是什么?