json处理工具
private ObjectMapper mapper = new ObjectMapper();
**对象转json**
```java
//
@Test
public void testJson1() throws JsonProcessingException {
User user = new User();
user.setId(1);
user.setAge(11);
user.setName("张三");
user.setUsername("zhangsan);
// 序列化
String json = mapper.writeValueAsString(user);
System.out.println("json = " + json);
}
`json转普通对象`**
```java
```java
@Test
public void testJson2() throws IOException {
User user = new User();
user.setId(1);
user.setAge(11);
user.setName("张三");
user.setUsername("zhangsan);
// 序列化
String json = mapper.writeValueAsString(user);
// 反序列化,接收两个参数:json数据,反序列化的目标类字节码
User result = mapper.readValue(json, User.class);
System.out.println("result = " + result);
}
json转集合
```java
@Test
public void testJson3() throws IOException {
User user = new User();
user.setId(1);
user.setAge(11);
user.setName("张三");
user.setUsername("zhangsan);
List<User> list = Arrays.asList(user, user);
// 序列化,得到对象集合的json字符串
String json = mapper.writeValueAsString(list);
// 反序列化,接收两个参数:json数据,反序列化的目标类字节码
List<User> users = mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, User.class));
for (User u : users) {
System.out.println("u = " + u);
}
}
json转任意复杂类型
@Test
public void testJson4() throws IOException {
User user = new User();
user.setId(1);
user.setAge(11);
user.setName("张三");
user.setUsername("zhangsan);
// 序列化,得到对象集合的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);
}
}