?DTO
package com.jt.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
/**
* User: ldj
* Date: 2022/3/6
* Time: 2:01
* Description: No Description
*/
@Data
public class UserDTO {
private String name;
private Integer age;
@JsonProperty("class")
private String clazz;
}
package com.jt.dto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.Map;
/**
* User: ldj
* Date: 2022/3/5
* Time: 22:09
* Description: No Description
*/
public class JsonToObject {
public static void main(String[] args) throws JsonProcessingException {
String json = "{\"student\":[{\"name\": \"lili\",\"age\": 15,\"class1\": \"高三7班\"},{\"name\": \"ldj\",\"age\": 5,\"class1\": \"幼儿园\"},{\"name\": \"jack\",\"age\": 16,\"class1\": \"初三5班\"}]}";
//jackson json -> Map
ObjectMapper objectMapper = new ObjectMapper();
Map<String, List<Object>> stringListMap1 = objectMapper.readValue(json, new TypeReference<Map<String, List<Object>>>() {
});
Map<String, Object> stringListMap2 = objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {
});
System.out.println("jacksonMap1:" + stringListMap1);
System.out.println("jacksonMap2:" + stringListMap2);
//jackson json -> List
String jsonBeans = "[{\"name\": \"lili\",\"age\": 15,\"class\": \"高三7班\"},{\"name\": \"ldj\",\"age\": 5,\"class\": \"幼儿园\"},{\"name\": \"jack\",\"age\": 16,\"class\": \"初三5班\"}]";
//UsersDTO usersDTO = objectMapper.readValue(jsonBeans, UsersDTO.class); 数组类型 反序列失败了
//System.out.println(usersDTO);
List<Object> students = objectMapper.readValue(jsonBeans, new TypeReference<List<Object>>() {
});
System.out.println("jacksonList:" + students);
String jsonBean = "{\"name\": \"lili\",\"age\": 15,\"class\": \"高三7班\"}";
UserDTO userDTO = objectMapper.readValue(jsonBean, UserDTO.class);
System.out.println(userDTO);
}
}
反序列化失败的DTO
package com.jt.dto;
import java.util.List;
/**
* User: ldj
* Date: 2022/3/6
* Time: 2:33
* Description: No Description
*/
public class UsersDTO {
public List<UserDTO> users;
}
|