所以我遇到了这个教程,用于将POJO序列化为json,然后将json文件反序列化回POJO。 http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
他使用这些有用的方法对我有用,但只对文件中的一个POJO:
//1. Convert Java object to JSON format
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), user);
//2. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\user.json"), User.class);
如何反序列化POJO列表?我的序列化文件如下所示:
[ {
"name" : {
"first" : "Wonder",
"last" : "Woman"
},
"ssn" : "123-456-7890",
"gender" : "FEMALE",
"verified" : false
}, {
"name" : {
"first" : "Bat",
"last" : "Man"
},
"ssn" : "321-456-0987",
"gender" : "FEMALE",
"verified" : true
}, {
"name" : {
"first" : "Super",
"last" : "Man"
},
"ssn" : "321-654-1111",
"gender" : "FEMALE",
"verified" : true
} ]
答案 0 :(得分:2)
一个选项(可能最简单)是定义一个包含User
列表的类:
public class Users
{
public User[] users;
}
然后执行
ObjectMapper mapper = new ObjectMapper();
Users users = mapper.readValue(new File("c:\\user.json"), Users.class);
另一种选择是迭代json数组,并捕获用户数组的每个元素,然后使用ObjectMapper.readValue(String content, Class<T> valueType)
,如下所示:
ObjectMapper mapper = new ObjectMapper();
InputStream stream = new FileInputStream("c:\\user.json");
User user;
JsonNode json = mapper.readTree(stream);
//NOTE: calling json.isArray() should return true.
for (JsonNode userJson : json)
{
user = mapper.readValue(userJson, User.class);
// use the constructed user...
}
注意:我没有对上述内容进行测试,请告知我是否有效。
答案 1 :(得分:1)
Hmmh?你试过了吗?
User[] users = mapper.readValue(new File("c:\\user.json"), User[].class);
答案 2 :(得分:0)
在您的顶级课程中,您有一系列人员。像这样的东西
class People {
public List<Person> persons;
}