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

1、目录结构

(java)idel中将对与json的相互转_第1张图片

2、导入包

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

(java)idel中将对与json的相互转_第2张图片

(java)idel中将对与json的相互转_第3张图片 

包的百度网盘

链接: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、结果

你可能感兴趣的:(java,json,前端)