对象与json字符串相互转化
在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}}
对象与json字符串相互转化的更多相关文章
- 使用Google的Gson实现对象和json字符串之间的转换
使用Google的Gson实现对象和json字符串之间的转换 需要gson.jar 1.JsonUtil.java package com.snail.json; import java.lang.r ...
- fastjson: json对象,json对象数组,javabean对象,json字符串之间的相互转化
fastjson: json对象,json对象数组,javabean对象,json字符串之间的相互转化 在开发过程中,经常需要和前端交互数据,数据交互的格式都是JSON,在此过程中免不了json字符串 ...
- JavaScript中JSON对象和JSON字符串的相互转化
一.JSON字符串转换为JSON对象 var str = '{"name":"cxh","sex":"man",&quo ...
- JS中JSON对象和JSON字符串的相互转化
转:http://www.cnblogs.com/wbyp/p/7086318.html 一.JSON字符串转换为JSON对象 var str = '{"name":"c ...
- jQuery中json对象与json字符串互换
json字符串转json对象:jQuery.parseJSON(jsonStr); json对象转json字符串:JSON.stringify(jsonObj); 根据“|”把字符串变成数组.spli ...
- 前端页面使用 Json对象与Json字符串之间的互相转换
前言 在前端页面很多时候都会用到Json这种格式的数据,最近没有前端,后端的我也要什么都要搞,对于Json对象与Json字符串之间的转换终于摸清楚了几种方式,归纳如下! 一:Json对象转换为json ...
- Json对象与Json字符串互转(转载)
一.jQuery插件支持的转换方式 1 $.paseJSON(jsonstr);//将json字符串转换为json对象 二.浏览器支持的转换方式(Firefox,Chrome,Opera,Safair ...
- [TypeScript] TypeScript对象转JSON字符串范例
[TypeScript] TypeScript对象转JSON字符串范例 Playground http://tinyurl.com/njbrnrv Samples class DataTable { ...
- json对象和json字符串有啥区别啊
json对象可以通过javascript存取属性!json对象装成json字符串经常用于前后台传输数据! 如果你在前台使用,那么Json对象可以通过xx.name来调用,如果是字符串,那么就是字符串了 ...
随机推荐
- HDU 6315 Naive Operations 【势能线段树】
<题目链接> 题目大意: 给出两个序列,a序列全部初始化为0,b序列为输入值.然后有两种操作,add x y就是把a数组[x,y]区间内全部+1,query x y是查询[x,y]区间内∑ ...
- 手模手配置Eslint,看懂脚手架中的Eslint
使用ESLint前:eslint是干嘛的,我这样写有什么问题,怎么还报错了,太麻烦想去掉这个插件,脚手架中关于eslint文件里的配置是什么意思?怎么设置配置项和规则达到自己想要的检测效果呢?怎么集成 ...
- Centos上Docker的安装及加速
#环境 :内核的版本必须大于3.10 #安装docker yum install epel-release -y yum install docker-ce ##安装docker-ce #配置文件 d ...
- 微信小程序(5)--阅读器
最近用微信小程序写了一个图书阅读器,可以实现左右滑动翻页,按钮翻页,上下滚动,切换背景,控制字体大小.以及记住设置好的状态,如页面再次进来保留上次的背景色和字体大小. 由于暂时没有真实的数据接口,所以 ...
- 一、小程序内嵌Html示例
小程序内嵌Html 1.下载wxParse:https://github.com/icindy/wxParse 2.下载完成后将插件目录下的wxParse文件夹拷贝到项目目录下 (文件夹明细) 3.全 ...
- setup PC not sleep when turn off display
- 描述一下JVM加载class文件的原理机制?
JVM中类的装载是由类加载器(ClassLoader)和它的子类来实现的,Java中的类加载器是一个重要的Java运行时系统组件,它负责在运行时查找和装入类文件中的类. 由于Java的跨平台性,经过编 ...
- JSON 简单例子
代码: json [ { "title" : "a", "num" : 1 }, { "title" : "b ...
- 理解Java构造器中的"this"
Calling Another Constructor if the first statement of a constructor has the form this(...), then the ...
- mui is not defined
vue项目中引用mui.js,我是在main.js中这样引入的, 结果报错 查找资料,最后在mui.js的最后添加了这样一句 这是因为mui并不能像jquery那样作为全局对象存在,加上wi ...