在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":"110@qq.com","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", "110@qq.com", car);
System.out.println(JsonSerializer.toJson(person));
System.out.println(JsonSerializer.toPrettyJson(person));

结果为:

{"id":1,"name":"yefengyu","email":"110@qq.com","car":{"id":1,"brand":"Rolls-Royce","date":"2019-06-22 13:25:30"}}
{
"id" : 1,
"name" : "yefengyu",
"email" : "110@qq.com",
"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", "1@qq.com",car);
Person p2 = new Person(2, "yefengyu", "2@qq.com",car);
Person p3 = new Person(3, "yefengyu", "3@qq.com",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":"1@qq.com","car":{"id":1,"brand":"Rolls-Royce","date":"2019-06-22 13:33:10"}},{"id":2,"name":"yefengyu","email":"2@qq.com","car":{"id":1,"brand":"Rolls-Royce","date":"2019-06-22 13:33:10"}},{"id":3,"name":"yefengyu","email":"3@qq.com","car":{"id":1,"brand":"Rolls-Royce","date":"2019-06-22 13:33:10"}}]
[ {
"id" : 1,
"name" : "yefengyu",
"email" : "1@qq.com",
"car" : {
"id" : 1,
"brand" : "Rolls-Royce",
"date" : "2019-06-22 13:33:10"
}
}, {
"id" : 2,
"name" : "yefengyu",
"email" : "2@qq.com",
"car" : {
"id" : 1,
"brand" : "Rolls-Royce",
"date" : "2019-06-22 13:33:10"
}
}, {
"id" : 3,
"name" : "yefengyu",
"email" : "3@qq.com",
"car" : {
"id" : 1,
"brand" : "Rolls-Royce",
"date" : "2019-06-22 13:33:10"
}
} ]

3、字符串转为单个对象

String json = "{\"id\":1,\"name\":\"yefengyu\",\"email\":\"110@qq.com\",\"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='110@qq.com', car=Car{id=1, brand='Rolls-Royce', date=Sat Jun 22 13:25:30 CST 2019}}

4、字符串转为对象集合

String list = "[{\"id\":1,\"name\":\"yefengyu\",\"email\":\"1@qq.com\",\"car\":{\"id\":1,\"brand\":\"Rolls-Royce\",\"date\":\"2019-06-22 13:33:10\"}},{\"id\":2,\"name\":\"yefengyu\",\"email\":\"2@qq.com\",\"car\":{\"id\":1,\"brand\":\"Rolls-Royce\",\"date\":\"2019-06-22 13:33:10\"}},{\"id\":3,\"name\":\"yefengyu\",\"email\":\"3@qq.com\",\"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='1@qq.com', car=Car{id=1, brand='Rolls-Royce', date=Sat Jun 22 13:33:10 CST 2019}}
Person{id=2, name='yefengyu', email='2@qq.com', car=Car{id=1, brand='Rolls-Royce', date=Sat Jun 22 13:33:10 CST 2019}}
Person{id=3, name='yefengyu', email='3@qq.com', car=Car{id=1, brand='Rolls-Royce', date=Sat Jun 22 13:33:10 CST 2019}}

最新文章

  1. HttpPost过程中使用的URLEncoder.encode(something, encode)
  2. 经受时间沉淀的15 个 Android 通用流行框架大全
  3. libnode 0.4.0 发布,C++ 语言版的 Node.js
  4. MySql视图、存储过程、函数、索引
  5. WCF初探-4:WCF消息交换模式之请求与答复模式
  6. SQL:查找被锁的表,以及锁表的SQL语句(重点推荐)
  7. BAT批处理(一)
  8. 监听Android CTS测试项解决方案(二)
  9. 通过gdb跟踪Linux内核装载和启动可执行程序过程
  10. read/write拥塞与非拥塞
  11. rapid-framework脚手架快速搭建springMVC框架项目
  12. 网络1712--c语言嵌套循环作业总结
  13. [NOI2015]软件包管理器
  14. mysql定时任务event——清理过期数据
  15. 开源网站流量统计系统Piwik源码分析——参数统计(一)
  16. python---redis实现自定义session
  17. 海明码 CRC冗余校验码
  18. 恢复Intellij idea删除的文件
  19. black-hole《XSS的原理分析与解剖》阅读笔记
  20. win10企业版永久激活2017怎么用

热门文章

  1. 使用jdbc查询防止出现中文乱码的方法
  2. BZOJ 1683.City skyline 城市地平线
  3. 工作流引擎 springmvc SSM 流程审批 Java Activiti 后台框架源码
  4. 软件工程第六组U-Helpβ版使用说明
  5. Ansible用法playbook
  6. 【串线篇】SQL映射文件select简单查询标签
  7. kaildi讲解
  8. 【学习笔记】整体二分(BZOJ2738矩阵乘法)
  9. Java Web入门二
  10. 安装RabbitMQ服务器及基本配置