1. 三者之间的关系
- Jason 是存储和交换文本信息的一种语法
- Jackson 是当前最广泛用来序列化 和 反序列化 json 的 java 开源框架
- ObjectMapper 是 Jackson 中最常用的一个API
2. ObjectMapper 主要方法
- writeValueAsString ( )
- readValue ( )
① Java与Json对象的相互转换
public class Person { int id; String name; String password; public Person(int id, String name, String password) { this.id = id; this.name = name; this.password = password; } } public class ObjectMapperTest { public static void main(String[] args) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); // Person对象转换为Json的格式 Person person = new Person(1, "小明", "2222"); String jsonString = objectMapper.writeValueAsString(person); System.out.println("JsonString: " + jsonString); // Json转换为Person对象 Person person1 = objectMapper.readValue(jsonString, Person.class); System.out.println(person1.toString()); } }
② Java与Json数组的相互转换
public class ObjectMapperTest { public static void main(String[] args) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); //Java数组转换为JSON数组 Person person1 = new Person(1, "张三", "33333"); Person person2 = new Person(2, "李四", "44444"); List<Person> personList = new ArrayList<>(); personList.add(person1); personList.add(person2); String jsonString = objectMapper.writeValueAsString(personList); System.out.println("JsonString List: " + jsonString); } }