json字符串与java对象的互转

首先要导入Jackson jar包并依赖
java对象转json字符串

public class MyTest {
    public static void main(String[] args) throws IOException {
        Student student = new Student();
        student.setName("张三");
        student.setAge(20);
        student.setFlag(true);
        student.setBirthday(new Date());
        //创建对象,有一个核心的对象
        ObjectMapper objectMapper = new ObjectMapper();
        //调用转换的方法,把java对象转换成json字符串
        String jsonStr = objectMapper.writeValueAsString(student);
        System.out.println(jsonStr);

        objectMapper.writeValue(new FileOutputStream("student.json"),student);
        objectMapper.writeValue(new FileWriter("student1.json"),student);
        objectMapper.writeValue(new File("student2.txt"),student);
    }
}

json字符串转java对象

public class MyTest2 {
    public static void main(String[] args) throws IOException {
        //json字符串转换成java对象
        Student student = new Student();
        //{"name":"zhangsan","age":20,"birthday":"new Data()"}
        String jsonStr="{\"name\":\"zhangsan\",\"age\":20}";
        ObjectMapper objectMapper = new ObjectMapper();
        //把json字符串转为java对象
        Student student1 = objectMapper.readValue(jsonStr, Student.class);
        System.out.println(student1);
    }
}

发布了12 篇原创文章 · 获赞 0 · 访问量 132
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 1024 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览