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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值