2014-05-20 39 views
0

轉換很多對象,如果我有簡單的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文件中獲取所有對象並將它們添加到列表中?對不起,我的英語不好

+1

你試圖解析的東西不是有效的JSON。你應該用數組或其他東西包裝它,比如:'[{「age」:29,...},{「age」:18,...}]'。關於如何解析數組,你可以閱讀[這裏](http://stackoverflow.com/questions/6349421/how-to-use-jackson-to-deserialise-an-array-of-objects) – SimY4

+0

哦,它簡單的方法 – mechanikos

+0

試試這個[link](http://stackoverflow.com/a/18959730/1283215) –

回答

1

如果你有User秒的JSON數組可以反序列化:

  • 由於User集合:

    om.readValue("myFile", new TypeReference<Collection<User>>() {});

  • 作爲Userarray

    om.readValue("myFile", User[].class);

你可能會需要你的JSON文件是固定的,由SimY4指出。

0

試試這個:

Class<?> clz = Class.forName(type); 
JavaType listType = mapper.getTypeFactory().constructCollectionType(List.class, clz); 
List <T> record = mapper.readValue(json, listType); 
+0

謝謝,我會試試 – mechanikos