一、Jackson

1、先看用法,代码跑起来自然就入门了。

① pom设置

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.0</version>
</dependency>

② 创建一个Person类如下:

Person.java

public class Person {
    private int age;
    private String name;
    private String school;
    private String major;

    public Person() {
    }

    public Person(int age, String name, String school, String major) {
        this.age = age;
        this.name = name;
        this.school = school;
        this.major = major;
    }

    public void setAge(int age) {
        this.age = age;
    }
    public void setName(String name) {
        this.name = name;
    }

    public void setSchool(String school) {
        this.school = school;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public String getSchool() {
        return school;
    }

    public String getMajor() {
        return major;
    }
}

 ③ JasonDemo.java

public class JacksonDemo {
    public static void Serialize() throws IOException {
        //使用ObjectMapper来转化对象json
        ObjectMapper mapper = new ObjectMapper();
        Person person = new Person(23,"张三","天津大学","光学工程");
        mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        //设置序列化后的格式,INDENT_OUTPUT表示缩进输出,true表示试该配置生效
        mapper.configure(SerializationFeature.INDENT_OUTPUT,true);
        //序列化结果输出为字符串
        String str = mapper.writeValueAsString(person);
        System.out.println(str);
        //序列化结果输出为文件输出
        mapper.writeValue(new File("Jackson.json"),person);
    }
    public static void main(String[] args) throws IOException {
        Serialize();
    }
}

注释mapper.configure一行输出:

//mapper.configure(SerializationFeature.INDENT_OUTPUT,true);

二、Gson

① pom配置

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

② 同person类

③ GsonDemo.java

这里还不会怎么直接写入json文件,直接找了字符串写入json文件的写法:

public class GsonDemo {
    public static void saveJson(String jsonStr, String fileName){
        /**
         * 将String类型写入到 *.json中
         */
        FileWriter writer;
        try{
            writer = new FileWriter(fileName);
            writer.write(jsonStr);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static String readJson(String fileName){
        /**
         * @param filename 读取 *.json文件
         */
        StringBuffer content = new StringBuffer();
        BufferedReader reader = null;
        try{
            reader = new BufferedReader(new FileReader(fileName));
            String line = null;
            while ((line=reader.readLine())!=null){
                content.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try{
                if(reader!=null){
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content.toString();
    }
    /**
     *   序列化
     */
    public static void Serial(){
        String fileName = "gson.json";
        Person person = new Person(23,"张三","天津大学","光学工程");
        String str = new Gson().toJson(person);
        //将对象进行实例化
        String jsonStr = new Gson().toJson(person);
        //保存json文件
        saveJson(jsonStr,fileName);
        System.out.println("序列化结果:"+jsonStr);
    }
    /**
     *    反序列化
     */
    public static void deSerial(){
        String fileName = "gson.json";
        //读取json文件
        String jsonStr = readJson(fileName);
        //将对象反序列化
        Person person1DeSerial = new Gson().fromJson(jsonStr,Person.class);
        System.out.println("反序列化结果:"+person1DeSerial);
    }

    public static void main(String[] args) {
        Serial();
        //等待一会
        try {
            Thread.sleep(1000);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        deSerial();
    }
}

在deSerial()方法中直接输出反序列化后的结果,需要重写toString()方法,使用apache.commoms重写的,在pom中加入: 

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.1</version>
</dependency>

最后输出:

三、性能比较–略(可以自行百度)

希望这套代码能帮助到像我一样刚入门的你(*^_^*)

 

 

 

 

 

 

 

 

 

本文地址:https://blog.csdn.net/Li_haiyu/article/details/107477810