使用Jackson的ObjectMapper对象的readValue和writeValueAsString方法可以进行转换。
对于简单基本类型或String类型的对象,使用上述方法可以满足。
但是如果要转换复杂类型Collection如 List<YourBean>,那么就需要先反序列化复杂类型为泛型的Collection Type。
如果是ArrayList<YourBean>那么使用ObjectMapper 的getTypeFactory().constructParametricType(collectionClass, elementClasses);
如果是HashMap<String,YourBean>那么 ObjectMapper 的getTypeFactory().constructParametricType(HashMap.class,String.class, YourBean.class);
例子如下,定义两个模型
package com.khlin.com.khlin.jackson.json.test; import java.util.List; public class Student { private String familyname; private String lastname; private int age; private String[] familyMembers; private Place hometown; public Place getHometown() {
return hometown;
} public void setHometown(Place hometown) {
this.hometown = hometown;
} public List<Place> getFavoritePlaces() {
return favoritePlaces;
} public void setFavoritePlaces(List<Place> favoritePlaces) {
this.favoritePlaces = favoritePlaces;
} private List<Place> favoritePlaces; public String getFamilyname() {
return familyname;
} public void setFamilyname(String familyname) {
this.familyname = familyname;
} public String getLastname() {
return lastname;
} public void setLastname(String lastname) {
this.lastname = lastname;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String[] getFamilyMembers() {
return familyMembers;
} public void setFamilyMembers(String[] familyMembers) {
this.familyMembers = familyMembers;
}
}
package com.khlin.com.khlin.jackson.json.test; public class Place { private String province; private String city; public String getProvince() {
return province;
} public void setProvince(String province) {
this.province = province;
} public String getCity() {
return city;
} public void setCity(String city) {
this.city = city;
}
}
转换代码:
ObjectMapper objectMapper = new ObjectMapper(); Place hometown = new Place();
hometown.setProvince("guangdong");
hometown.setCity("jieyang"); Place place1 = new Place();
place1.setProvince("fujian");
place1.setCity("amoy"); Place place2 = new Place();
place2.setProvince("zhejiang");
place2.setCity("hangzhou"); List<Place> places = new ArrayList<Place>();
places.add(place1);
places.add(place2);
Student student = generateStudent("dacui", "lin", hometown, places); Student student2 = generateStudent("ku", "lee", hometown, places); List<Student> students = new ArrayList<Student>();
students.add(student);
students.add(student2); String result = objectMapper.writeValueAsString(students);
System.out.println(result); JavaType javaType = objectMapper.getTypeFactory()
.constructParametricType(ArrayList.class, Student.class); List<Student> mapperStudents = objectMapper.readValue(result,
javaType);
Student mapperStudent1 = mapperStudents.get(0);
Student mapperStudent2 = mapperStudents.get(1);
System.out.println("success");