Jackson入门程序
精华
小牛编辑
147浏览
2023-03-14
1 下载Jackson包
要使用Jackson库,先下载Jackson包并导入到项目中
下载jackson-2.8.9
2 Jackson入门程序
2.1 编写核心类
MainApp:
package cn.xnip.jackson;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
/**
* 小牛知识库网 - https://www.xnip.cn
*/
public class MainApp {
public static void main(String args[]) {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"eric\", \"age\":21}";
try{
//把JSON转换为Java对象
Student student = mapper.readValue(jsonString, Student.class);
System.out.println(student);
//把Java对象为JSON
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+ " ]";
}
}