使用Jackson的ObjectMapper对象的readValue和writeValueAsString方法可以进行转换。
对于简单基本类型或String类型的对象,使用上述方法可以满足。
但是如果要转换复杂类型Collection如 List
如果是ArrayList
如果是HashMap
例子如下,定义两个模型
1 package com.khlin.com.khlin.jackson.json.test; 2 3 import java.util.List; 4 5 public class Student { 6 7 private String familyname; 8 9 private String lastname; 10 11 private int age; 12 13 private String[] familyMembers; 14 15 private Place hometown; 16 17 public Place getHometown() { 18 return hometown; 19 } 20 21 public void setHometown(Place hometown) { 22 this.hometown = hometown; 23 } 24 25 public ListgetFavoritePlaces() { 26 return favoritePlaces; 27 } 28 29 public void setFavoritePlaces(List favoritePlaces) { 30 this.favoritePlaces = favoritePlaces; 31 } 32 33 private List favoritePlaces; 34 35 public String getFamilyname() { 36 return familyname; 37 } 38 39 public void setFamilyname(String familyname) { 40 this.familyname = familyname; 41 } 42 43 public String getLastname() { 44 return lastname; 45 } 46 47 public void setLastname(String lastname) { 48 this.lastname = lastname; 49 } 50 51 public int getAge() { 52 return age; 53 } 54 55 public void setAge(int age) { 56 this.age = age; 57 } 58 59 public String[] getFamilyMembers() { 60 return familyMembers; 61 } 62 63 public void setFamilyMembers(String[] familyMembers) { 64 this.familyMembers = familyMembers; 65 } 66 }
1 package com.khlin.com.khlin.jackson.json.test; 2 3 public class Place { 4 5 private String province; 6 7 private String city; 8 9 public String getProvince() { 10 return province; 11 } 12 13 public void setProvince(String province) { 14 this.province = province; 15 } 16 17 public String getCity() { 18 return city; 19 } 20 21 public void setCity(String city) { 22 this.city = city; 23 } 24 }
转换代码:
1 ObjectMapper objectMapper = new ObjectMapper(); 2 3 Place hometown = new Place(); 4 hometown.setProvince("guangdong"); 5 hometown.setCity("jieyang"); 6 7 Place place1 = new Place(); 8 place1.setProvince("fujian"); 9 place1.setCity("amoy"); 10 11 Place place2 = new Place(); 12 place2.setProvince("zhejiang"); 13 place2.setCity("hangzhou"); 14 15 Listplaces = new ArrayList (); 16 places.add(place1); 17 places.add(place2); 18 Student student = generateStudent("dacui", "lin", hometown, places); 19 20 Student student2 = generateStudent("ku", "lee", hometown, places); 21 22 List students = new ArrayList (); 23 students.add(student); 24 students.add(student2); 25 26 String result = objectMapper.writeValueAsString(students); 27 System.out.println(result); 28 29 JavaType javaType = objectMapper.getTypeFactory() 30 .constructParametricType(ArrayList.class, Student.class); 31 32 List mapperStudents = objectMapper.readValue(result, 33 javaType); 34 Student mapperStudent1 = mapperStudents.get(0); 35 Student mapperStudent2 = mapperStudents.get(1); 36 System.out.println("success");