轉換很多對象,如果我有簡單的JSON與Json。從一個JSON
{
"age":29,
"messages":["msg 1","msg 2","msg 3"],
"name":"mkyong"
}
我用這個代碼
public class JacksonExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try {
// read from file, convert it to user class
User user = mapper.readValue(new File("c:\\user.json"), User.class);
// display to console
System.out.println(user);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
,並得到,一個對象。但如果我有
{
"age":29,
"messages":["msg 1","msg 2","msg 3"],
"name":"alice"
}
{
"age":18,
"messages":["msg 4","msg 5","msg 6"],
"name":"bob"
}
如何從一個json文件中獲取所有對象並將它們添加到列表中?對不起,我的英語不好
你試圖解析的東西不是有效的JSON。你應該用數組或其他東西包裝它,比如:'[{「age」:29,...},{「age」:18,...}]'。關於如何解析數組,你可以閱讀[這裏](http://stackoverflow.com/questions/6349421/how-to-use-jackson-to-deserialise-an-array-of-objects) – SimY4
哦,它簡單的方法 – mechanikos
試試這個[link](http://stackoverflow.com/a/18959730/1283215) –