我们创建一个Student类。将创建一个JSON字符串学生的详细信息,并将其反序列化到学生的对象,然后将其序列化到JSON字符串。
public class Student { private String name; private Integer age; public Student(){} public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString(){ return "Student [ name: "+name+", age: "+ age+ " ]"; } }
public class JacksonTester { public static void main(String[] args) { //可重复使用的对象 ObjectMapper mapper = new ObjectMapper(); String jsonString= "{"name":"Mahesh", "age":21}"; //map json to student try{ //反序列化JSON到对象,通过JSON字符串和对象类型作为参数JSON来源 Student student =mapper.readValue(jsonString,Student.class); System.out.println(student); mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT); //使用writeValueAsString()方法来获取对象的JSON字符串表示 jsonString = mapper.writeValueAsString(student); System.out.println(jsonString); }catch (JsonParseException e){ e.printStackTrace(); }catch (JsonMappingException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } } }
结果:
"C:Program FilesJavajdk1.8.0_191injava.exe" ... Student [ name: Mahesh, age: 21 ] { "name" : "Mahesh", "age" : 21 } Process finished with exit code 0