赞
踩
// 对象转json
private ObjectMapper mapper = new ObjectMapper();
@Test
public void testJson() throws JsonProcessingException {
User user = new User();
user.setId(8L);
user.setAge(21);
user.setName("柳岩");
user.setUserName("liuyan");
// 序列化
String json = mapper.writeValueAsString(user);
System.out.println("json = " + json);
}
// json转对象
private ObjectMapper mapper = new ObjectMapper();
@Test
public void testJson() throws IOException {
User user = new User();
user.setId(8L);
user.setAge(21);
user.setName("柳岩");
user.setUserName("liuyan");
// 序列化
String json = mapper.writeValueAsString(user);
// 反序列化,接收两个参数:json数据,反序列化的目标类字节码
User result = mapper.readValue(json, User.class);
System.out.println("result = " + result);
}
// json转集合
private ObjectMapper mapper = new ObjectMapper();
@Test
public void testJson() throws IOException {
User user = new User();
user.setId(8L);
user.setAge(21);
user.setName("柳岩");
user.setUserName("liuyan");
// 序列化,得到对象集合的json字符串
String json = mapper.writeValueAsString(Arrays.asList(user, user));
// 反序列化,接收两个参数:json数据,反序列化的目标类字节码
List<User> users = mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, User.class));
for (User u : users) {
System.out.println("u = " + u);
}
}
//json转任意复杂类型
private ObjectMapper mapper = new ObjectMapper();
@Test
public void testJson() throws IOException {
User user = new User();
user.setId(8L);
user.setAge(21);
user.setName("柳岩");
user.setUserName("liuyan");
// 序列化,得到对象集合的json字符串
String json = mapper.writeValueAsString(Arrays.asList(user, user));
// 反序列化,接收两个参数:json数据,反序列化的目标类字节码
List<User> users = mapper.readValue(json, new TypeReference<List<User>>(){});
for (User u : users) {
System.out.println("u = " + u);
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。