我的json文件包含多个对象:
[
{
"name":"Move",
"$$hashKey":"object:79",
"time":11.32818,
"endTime":18.615535
},
{
"name":"First Red Flash",
"$$hashKey":"object:77",
"time":15.749153
},
{
"name":"Pills",
"subEventTypes":[
"pull down bottle",
"unscrew lid",
"dump pills out",
"screw lid on",
"put bottle away"
],
"$$hashKey":"object:82",
"time":25.130175,
"subEventSplits":[
26.092057,
27.425881,
31.841594,
34.268093
],
"endTime":36.234827
}
}
有没有办法使用Jackson解析这个Json文件?或者是否有其他可用的库允许我以这种格式解析Json文件? 到目前为止,这是我的代码:
File file = new File("data.json");
JsonFactory jsonFactory = new JsonFactory();
JsonParser parser = jsonFactory.createJsonParser(file);
while(parser.nextToken()!=JsonToken.END_OBJECT)
{
//how to read each token
}
答案 0 :(得分:2)
杰克逊应该解析你提到的JSON文件。创建一个类,如下所示
Class Holder {
String name;
List<String> subEventTypes = new ArrayList<>();
String $$hashKey;
Double time;
List<Double> subEventSplits = new ArrayList<>()
DOuble endTime;
}
Class MapperClass{
List<Holder> list = new ArrayList<>();
}
解析它如下所示
ObjectMapper mapper = new ObjectMapper();
//JSON from file to Object
MapperClass values = mapper.readValue(new File("c:\\values.json"), MapperClass.class);
有关详细信息,请参阅此link
答案 1 :(得分:1)
您可以使用树模型,它就像
ObjectMapper m = new ObjectMapper();
JsonNode rootNode = m.readTree(new File("data.json"));
Iterator<JsonNode> it = rootNode.getElements();
while(it.hasNext()) {
System.out.println("element : " + it.next().toString());
}
然后你会看到你想要的东西:)