json 与 java 的转换的几种调用方法案例分析

1. 创建实例类

package com.fy.test;

public class Student {
    
    

    private int id;
    private String name;
    private boolean sex;

    public Student(int id, String name, boolean sex) {
    
    
        this.id = id;
        this.name = name;
        this.sex = sex;
    }

    public Student() {
    
    

    }

    public Student(int i, String zhu) {
    
    

    }

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

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

    public boolean isSex() {
    
    
        return sex;
    }

    public void setSex(boolean sex) {
    
    
        this.sex = sex;
    }
}

实现类

package com.fy.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.lang.management.ManagementPermission;

/**
 * json 与 java 的转换
 * 调用方法:writeValueAsString(Object o)
 *          writeValue(OutputStream os,Object o)
 *          writeValue(Writer,Object o)
 *          writeValue(File f,Object o)
 */
public class TestJackson {
    
    
    @Test
    public void f() throws Exception {
    
    
        //创建Jackson的核心对象ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //创建要转换成json数据的java对象
        Student student = new Student(12,"zhu",true);
        //调用writeValue(),将java对象写到指定的文件中
//        mapper.writeValue(new File("C:\\Users\\Administrator\\Desktop\\test.txt"),student);
        mapper.writeValue(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\b.txt"), student);
        mapper.writeValue(new FileWriter("C:\\Users\\Administrator\\Desktop\\a.txt"),student);




    }
}

3. 运行结果,成功写入文件

运行结果

a

猜你喜欢

转载自blog.csdn.net/zhu_fangyuan/article/details/108720321