(java)idel中将对与json的相互转

本文介绍了如何在Java项目中组织目录结构,导入外部包,创建Dog和Person类,并展示了如何使用Jackson库进行对象序列化和反序列化,实现从Person类到JSON字符串的转换。
摘要由CSDN通过智能技术生成

1、目录结构

2、导入包

 在模块下面建立lib目录将包导入模块中

 

包的百度网盘

链接:https://pan.baidu.com/s/1abNF8cOTeNb00rM7tp04iQ?pwd=39wc 
提取码:39wc 
 

3、建立两个测试类person和dog类



public class Dog {
    private String name;
    private int age;

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    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 Dog() {
    }

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
}



//person类------------------------------------------------------

public class Person {
    private String name;
    private int age;
    private Dog dog;


    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", dog=" + dog +
                '}';
    }

    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 Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public Person() {
    }

    public Person(String name, int age, Dog dog) {
        this.name = name;
        this.age = age;
        this.dog = dog;
    }
}

4、建立测试类



import com.atlili.projo.Dog;
import com.atlili.projo.Person;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

public class TestJson {
    @Test
    public void test1() throws JsonProcessingException {
        //实例化person
        Dog dog = new Dog("xiaohei",12);
        Person p = new Person("tom",10,dog);
        //将person对象转化为字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String string = objectMapper.writeValueAsString(p);
        System.out.println(string);
    }

    @Test
    public void test2() throws JsonProcessingException {
        String personstr="{\"name\":\"tom\",\"age\":10,\"dog\":{\"name\":\"xiaohei\",\"age\":12}}";
        ObjectMapper objectMapper = new ObjectMapper();
        Person person = objectMapper.readValue(personstr, Person.class);
        System.out.println(person);
    }
}

5、结果

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值