在 java 编程中, JSON 字符串和对象的相互转化十分常用, 下面我们就对象如何转化为 JSON 字符串以及 JSON 字符串如何转化为对象进行简要介绍, 以便在代码中能方便使用.
1, 依赖
本次介绍的方法依赖 jackson, 这是非常通用的 JSON 工具.
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>2.9.8</version>
- </dependency>
2, 实体
下面我们编写一个稍微复杂的实体, 以便进行测试.
- package com.yefengyu.utils;
- import java.util.Date;
- public class Car
- {
- private Integer id;
- private String brand;
- private Date date;
- public Car()
- {
- }
- public Car(Integer id, String brand, Date date)
- {
- this.id = id;
- this.brand = brand;
- this.date = date;
- }
- public Integer getId()
- {
- return id;
- }
- public void setId(Integer id)
- {
- this.id = id;
- }
- public String getBrand()
- {
- return brand;
- }
- public void setBrand(String brand)
- {
- this.brand = brand;
- }
- public Date getDate()
- {
- return date;
- }
- public void setDate(Date date)
- {
- this.date = date;
- }
- @Override
- public String toString()
- {
- return "Car{" +
- "id=" + id +
- ", brand='" + brand + '\'' +
- ", date=" + date +
- '}';
- }
- }
上面编写了一个 Car 类, 下面再编写一个 Person 类.
- package com.yefengyu.utils;
- public class Person
- {
- private Integer id;
- private String name;
- private String email;
- private Car car;
- public Person()
- {
- }
- public Person(Integer id, String name, String email, Car car)
- {
- this.id = id;
- this.name = name;
- this.email = email;
- this.car = car;
- }
- public Integer getId()
- {
- return id;
- }
- public void setId(Integer id)
- {
- this.id = id;
- }
- public String getName()
- {
- return name;
- }
- public void setName(String name)
- {
- this.name = name;
- }
- public String getEmail()
- {
- return email;
- }
- public void setEmail(String email)
- {
- this.email = email;
- }
- public Car getCar()
- {
- return car;
- }
- public void setCar(Car car)
- {
- this.car = car;
- }
- @Override
- public String toString()
- {
- return "Person{" +
- "id=" + id +
- ", name='" + name + '\'' +
- ", email='" + email + '\'' +
- ", car=" + car +
- '}';
- }
- }
注意的是: 必须有无参构造函数. 若无则在字符串转为对象的时候:
- com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.yefengyu.utils.Person` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
- at [Source: (String)"{"id":1,"name":"yefengyu","email":"[email protected]","car":{"id":1,"brand":"Rolls-Royce","date":"2019-06-22 13:25:30"}}"; line: 1, column: 2]
3, 工具
下面的代码是一个工具类, 实现了 JSON 字符串到对象的相互转化过程.
- package com.yefengyu.utils;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.core.type.TypeReference;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- // 使用 final 关键字防止继承
- public final class JsonSerializer
- {
- private static final ObjectMapper MAPPER;
- static
- {
- MAPPER = new ObjectMapper();
- MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));// 日期格式化
- }
- private JsonSerializer()
- {
- // 防止 new 对象
- }
- // 对象转化为 JSON 字符串
- public static String toJson(Object object)
- {
- try
- {
- return MAPPER.writeValueAsString(object);
- }
- catch (JsonProcessingException e)
- {
- e.printStackTrace();
- }
- return null;
- }
- // 对象转化为 JSON 字符串, 并格式化输出
- public static String toPrettyJson(Object object)
- {
- try
- {
- return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(object);
- }
- catch (JsonProcessingException e)
- {
- e.printStackTrace();
- }
- return null;
- }
- // 字符串转为单个对象
- public static <T> T fromJson(String JSON, Class<T> clazz)
- {
- if (JSON == null || JSON.trim().isEmpty() || clazz == null)
- {
- return null;
- }
- try
- {
- return MAPPER.readValue(JSON, clazz);
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- return null;
- }
- // 字符串转为对象, 比如对象列表
- public static <T> T fromJson(String JSON, TypeReference<T> typeReference)
- {
- if (JSON == null || JSON.trim().isEmpty() || typeReference == null)
- {
- return null;
- }
- try
- {
- return MAPPER.readValue(JSON, typeReference);
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- return null;
- }
- }
4, 测试
1, 单个对象转化为 JSON 字符串
- Car car = new Car(1,"Rolls-Royce",new Date());
- Person person = new Person(1, "yefengyu", "[email protected]", car);
- System.out.println(JsonSerializer.toJson(person));
- System.out.println(JsonSerializer.toPrettyJson(person));
结果为:
- {"id":1,"name":"yefengyu","email":"[email protected]","car":{"id":1,"brand":"Rolls-Royce","date":"2019-06-22 13:25:30"}}
- {
- "id" : 1,
- "name" : "yefengyu",
- "email" : "[email protected]",
- "car" : {
- "id" : 1,
- "brand" : "Rolls-Royce",
- "date" : "2019-06-22 13:25:30"
- }
- }
2, 集合对象转化为 JSON 字符串
- Car car = new Car(1,"Rolls-Royce",new Date());
- List<Person> personList = new ArrayList<>();
- Person p1 = new Person(1, "yefengyu", "[email protected]",car);
- Person p2 = new Person(2, "yefengyu", "[email protected]",car);
- Person p3 = new Person(3, "yefengyu", "[email protected]",car);
- personList.add(p1);
- personList.add(p2);
- personList.add(p3);
- System.out.println(JsonSerializer.toJson(personList));
- System.out.println(JsonSerializer.toPrettyJson(personList));
结果为:
- [{"id":1,"name":"yefengyu","email":"[email protected]","car":{"id":1,"brand":"Rolls-Royce","date":"2019-06-22 13:33:10"}},{"id":2,"name":"yefengyu","email":"[email protected]","car":{"id":1,"brand":"Rolls-Royce","date":"2019-06-22 13:33:10"}},{"id":3,"name":"yefengyu","email":"[email protected]","car":{"id":1,"brand":"Rolls-Royce","date":"2019-06-22 13:33:10"}}]
- [ {
- "id" : 1,
- "name" : "yefengyu",
- "email" : "[email protected]",
- "car" : {
- "id" : 1,
- "brand" : "Rolls-Royce",
- "date" : "2019-06-22 13:33:10"
- }
- }, {
- "id" : 2,
- "name" : "yefengyu",
- "email" : "[email protected]",
- "car" : {
- "id" : 1,
- "brand" : "Rolls-Royce",
- "date" : "2019-06-22 13:33:10"
- }
- }, {
- "id" : 3,
- "name" : "yefengyu",
- "email" : "[email protected]",
- "car" : {
- "id" : 1,
- "brand" : "Rolls-Royce",
- "date" : "2019-06-22 13:33:10"
- }
- } ]
3, 字符串转为单个对象
- String JSON = "{\"id\":1,\"name\":\"yefengyu\",\"email\":\"[email protected]\",\"car\":{\"id\":1,\"brand\":\"Rolls-Royce\",\"date\":\"2019-06-22 13:25:30\"}}";
- System.out.println(JsonSerializer.fromJson(JSON, Person.class));
结果如下:
Person{id=1, name='yefengyu', email='[email protected]', car=Car{id=1, brand='Rolls-Royce', date=Sat Jun 22 13:25:30 CST 2019}}
4, 字符串转为对象集合
- String list = "[{\"id\":1,\"name\":\"yefengyu\",\"email\":\"[email protected]\",\"car\":{\"id\":1,\"brand\":\"Rolls-Royce\",\"date\":\"2019-06-22 13:33:10\"}},{\"id\":2,\"name\":\"yefengyu\",\"email\":\"[email protected]\",\"car\":{\"id\":1,\"brand\":\"Rolls-Royce\",\"date\":\"2019-06-22 13:33:10\"}},{\"id\":3,\"name\":\"yefengyu\",\"email\":\"[email protected]\",\"car\":{\"id\":1,\"brand\":\"Rolls-Royce\",\"date\":\"2019-06-22 13:33:10\"}}]";
- List<Person> persons = JsonSerializer.fromJson(list, new TypeReference<List<Person>>()
- {
- });
- for (Person person : persons)
- {
- System.out.println(person);
- }
结果如下:
- Person{
- id=1, name='yefengyu', email='[email protected]', car=Car{
- id=1, brand='Rolls-Royce', date=Sat Jun 22 13:33:10 CST 2019
- }
- }
- Person{
- id=2, name='yefengyu', email='[email protected]', car=Car{
- id=1, brand='Rolls-Royce', date=Sat Jun 22 13:33:10 CST 2019
- }
- }
- Person{
- id=3, name='yefengyu', email='[email protected]', car=Car{
- id=1, brand='Rolls-Royce', date=Sat Jun 22 13:33:10 CST 2019
- }
- }
来源: http://www.bubuko.com/infodetail-3100265.html