Jackson 简明教程
Jackson - First Application
在开始了解 jackson 库的详细信息之前,让我们先在实际应用中看看它。在这个例子中,我们创建了 Student 类。我们将使用学生的详细信息创建一个 JSON 字符串,并将其反序列化为 student 对象,然后将其序列化为 JSON 字符串。
Before going into the details of the jackson library, let’s see an application in action. In this example, we’ve created Student class. We’ll create a JSON string with student details and deserialize it to student object and then serialize it to an JSON String.
在 C:>Jackson_WORKSPACE 中创建一个名为 JacksonTester 的 java 类文件。
Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
文件:JacksonTester.java
File: JacksonTester.java
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";
//map json to student
try{
Student student = mapper.readValue(jsonString, Student.class);
System.out.println(student);
jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);
System.out.println(jsonString);
}
catch (JsonParseException e) { e.printStackTrace();}
catch (JsonMappingException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
}
class Student {
private String name;
private int 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+ " ]";
}
}
Verify the result
Verify the result
使用 javac 编译器编译类,如下所示:
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
现在运行 jacksonTester 查看结果:
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
验证输出
Verify the Output
Student [ name: Mahesh, age: 21 ]
{
"name" : "Mahesh",
"age" : 21
}
Steps to remember
以下是需要考虑的重要步骤。
Following are the important steps to be considered here.
Step 1: Create ObjectMapper object.
创建 ObjectMapper 对象。这是一个可重用的对象。
Create ObjectMapper object. It is a reusable object.
ObjectMapper mapper = new ObjectMapper();
Step 2: DeSerialize JSON to Object.
使用 readValue() 方法从 JSON 中获取对象。将 json 字符串/json 字符串的源和对象类型作为参数传递。
Use readValue() method to get the Object from the JSON. Pass json string/ source of json string and object type as parameter.
//Object to JSON Conversion
Student student = mapper.readValue(jsonString, Student.class);