1、目录结构
2、导入包
在模块下面建立lib目录将包导入模块中
包的百度网盘
链接:https://pan.baidu.com/s/1abNF8cOTeNb00rM7tp04iQ?pwd=39wc
提取码:39wc
3、建立两个测试类person和dog类
public class Dog {private String name;private int age;@Overridepublic 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;@Overridepublic 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 {@Testpublic void test1() throws JsonProcessingException {//实例化personDog 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);}@Testpublic 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、结果