Jackson入门程序

1 下载Jackson包

要使用Jackson库,先下载Jackson包并导入到项目中

下载jackson-2.8.9

2 Jackson入门程序

2.1 编写核心类

MainApp:

package com.yiidian.jackson;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * 一点教程网 - http://www.yiidian.com
 */
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+ " ]";
    }
}

2.2 运行测试

推荐好课