public static void main(String[] args) {
try {
ObjectMapper objectMapper = new ObjectMapper();
String json = "{\"name\":\"张三\",\"age\":23,\"address\":\"深圳市\"}";
User zhang = objectMapper.readValue(json, User.class);
System.out.println(zhang.getName() + "\n" + zhang.getAge() + "\n" + zhang.getAddress());
} catch(IOException e) {
e.printStackTrace();
2. json转list对象
public static void main(String[] args) {
try {
ObjectMapper objectMapper = new ObjectMapper();
//JSON转list
String listJson = "[{\"name\":\"张三\",\"age\":21,\"address\":\"深圳\"}," + "{\"name\":\"李四\",\"age\":11,\"address\":\"武汉\"}," + "{\"name\":\"王五\",\"age\":31,\"address\":\"北京\"}]";
JavaType javaType1 = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, User.class);
List < User > userList = (List < User > ) objectMapper.readValue(listJson, javaType1);
for (User user1: userList) {
System.out.println(user1.getName() + "\t" + user1.getAge() + "\t" + user1.getAddress());
} catch(IOException e) {
e.printStackTrace();
3. json转map对象
public static void main(String[] args) {
try {
ObjectMapper objectMapper = new ObjectMapper();
//JSON转map
String mapJson = "{\"one\":{\"name\":\"张三\",\"age\":21,\"address\":\"深圳\"}," + "\"two\":{\"name\":\"李四\",\"age\":11,\"address\":\"武汉\"}," + "\"three\":{\"name\":\"王五\",\"age\":31,\"address\":\"北京\"}}";
JavaType javaType2 = objectMapper.getTypeFactory().constructParametricType(HashMap.class, String.class, User.class);
Map < String,User > userMap = (Map < String, User > ) objectMapper.readValue(mapJson, javaType2);
User one = userMap.get("one");
User two = userMap.get("two");
User three = userMap.get("three");
System.out.println(one.getName() + "\t" + one.getAge() + "\t" + one.getAddress());
System.out.println(two.getName() + "\t" + two.getAge() + "\t" + two.getAddress());
System.out.println(three.getName() + "\t" + three.getAge() + "\t" + three.getAddress());
} catch(IOException e) {
e.printStackTrace();
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。