在java编程中,json字符串和对象的相互转化十分常用,下面我们就对象如何转化为json字符串以及json字符串如何转化为对象进行简要介绍,以便在代码中能方便使用。

1、依赖


本次介绍的方法依赖jackson,这是非常通用的json工具。

  1. <dependency>
  2. <groupId>com.fasterxml.jackson.core</groupId>
  3. <artifactId>jackson-databind</artifactId>
  4. <version>2.9.8</version>
  5. </dependency>

2、实体


下面我们编写一个稍微复杂的实体,以便进行测试。

  1. package com.yefengyu.utils;
  2.  
  3. import java.util.Date;
  4.  
  5. public class Car
  6. {
  7. private Integer id;
  8.  
  9. private String brand;
  10.  
  11. private Date date;
  12.  
  13. public Car()
  14. {
  15. }
  16.  
  17. public Car(Integer id, String brand, Date date)
  18. {
  19. this.id = id;
  20. this.brand = brand;
  21. this.date = date;
  22. }
  23.  
  24. public Integer getId()
  25. {
  26. return id;
  27. }
  28.  
  29. public void setId(Integer id)
  30. {
  31. this.id = id;
  32. }
  33.  
  34. public String getBrand()
  35. {
  36. return brand;
  37. }
  38.  
  39. public void setBrand(String brand)
  40. {
  41. this.brand = brand;
  42. }
  43.  
  44. public Date getDate()
  45. {
  46. return date;
  47. }
  48.  
  49. public void setDate(Date date)
  50. {
  51. this.date = date;
  52. }
  53.  
  54. @Override
  55. public String toString()
  56. {
  57. return "Car{" +
  58. "id=" + id +
  59. ", brand='" + brand + '\'' +
  60. ", date=" + date +
  61. '}';
  62. }
  63. }

上面编写了一个Car类,下面再编写一个Person类。

  1. package com.yefengyu.utils;
  2.  
  3. public class Person
  4. {
  5. private Integer id;
  6.  
  7. private String name;
  8.  
  9. private String email;
  10.  
  11. private Car car;
  12.  
  13. public Person()
  14. {
  15. }
  16.  
  17. public Person(Integer id, String name, String email, Car car)
  18. {
  19. this.id = id;
  20. this.name = name;
  21. this.email = email;
  22. this.car = car;
  23. }
  24.  
  25. public Integer getId()
  26. {
  27. return id;
  28. }
  29.  
  30. public void setId(Integer id)
  31. {
  32. this.id = id;
  33. }
  34.  
  35. public String getName()
  36. {
  37. return name;
  38. }
  39.  
  40. public void setName(String name)
  41. {
  42. this.name = name;
  43. }
  44.  
  45. public String getEmail()
  46. {
  47. return email;
  48. }
  49.  
  50. public void setEmail(String email)
  51. {
  52. this.email = email;
  53. }
  54.  
  55. public Car getCar()
  56. {
  57. return car;
  58. }
  59.  
  60. public void setCar(Car car)
  61. {
  62. this.car = car;
  63. }
  64.  
  65. @Override
  66. public String toString()
  67. {
  68. return "Person{" +
  69. "id=" + id +
  70. ", name='" + name + '\'' +
  71. ", email='" + email + '\'' +
  72. ", car=" + car +
  73. '}';
  74. }
  75. }

注意的是:必须有无参构造函数。若无则在字符串转为对象的时候:

  1. 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)
  2. 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字符串到对象的相互转化过程。

  1. package com.yefengyu.utils;
  2.  
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.core.type.TypeReference;
  5. import com.fasterxml.jackson.databind.ObjectMapper;
  6.  
  7. import java.io.IOException;
  8. import java.text.SimpleDateFormat;
  9.  
  10. //使用final关键字防止继承
  11. public final class JsonSerializer
  12. {
  13. private static final ObjectMapper MAPPER;
  14.  
  15. static
  16. {
  17. MAPPER = new ObjectMapper();
  18. MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));//日期格式化
  19. }
  20.  
  21. private JsonSerializer()
  22. {
  23. //防止new对象
  24. }
  25.  
  26. //对象转化为json字符串
  27. public static String toJson(Object object)
  28. {
  29. try
  30. {
  31. return MAPPER.writeValueAsString(object);
  32. }
  33. catch (JsonProcessingException e)
  34. {
  35. e.printStackTrace();
  36. }
  37. return null;
  38. }
  39.  
  40. //对象转化为json字符串,并格式化输出
  41. public static String toPrettyJson(Object object)
  42. {
  43. try
  44. {
  45. return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(object);
  46. }
  47. catch (JsonProcessingException e)
  48. {
  49. e.printStackTrace();
  50. }
  51. return null;
  52. }
  53.  
  54. //字符串转为单个对象
  55. public static <T> T fromJson(String json, Class<T> clazz)
  56. {
  57. if (json == null || json.trim().isEmpty() || clazz == null)
  58. {
  59. return null;
  60. }
  61.  
  62. try
  63. {
  64. return MAPPER.readValue(json, clazz);
  65. }
  66. catch (IOException e)
  67. {
  68. e.printStackTrace();
  69. }
  70. return null;
  71. }
  72.  
  73. //字符串转为对象,比如对象列表
  74. public static <T> T fromJson(String json, TypeReference<T> typeReference)
  75. {
  76. if (json == null || json.trim().isEmpty() || typeReference == null)
  77. {
  78. return null;
  79. }
  80.  
  81. try
  82. {
  83. return MAPPER.readValue(json, typeReference);
  84. }
  85. catch (IOException e)
  86. {
  87. e.printStackTrace();
  88. }
  89. return null;
  90. }
  91. }

4、测试


1、单个对象转化为json字符串

  1. Car car = new Car(1,"Rolls-Royce",new Date());
  2. Person person = new Person(1, "yefengyu", "110@qq.com", car);
  3. System.out.println(JsonSerializer.toJson(person));
  4. System.out.println(JsonSerializer.toPrettyJson(person));

结果为:

  1. {"id":1,"name":"yefengyu","email":"110@qq.com","car":{"id":1,"brand":"Rolls-Royce","date":"2019-06-22 13:25:30"}}
  2. {
  3. "id" : 1,
  4. "name" : "yefengyu",
  5. "email" : "110@qq.com",
  6. "car" : {
  7. "id" : 1,
  8. "brand" : "Rolls-Royce",
  9. "date" : "2019-06-22 13:25:30"
  10. }
  11. }

2、集合对象转化为json字符串

  1. Car car = new Car(1,"Rolls-Royce",new Date());
  2.  
  3. List<Person> personList = new ArrayList<>();
  4.  
  5. Person p1 = new Person(1, "yefengyu", "1@qq.com",car);
  6. Person p2 = new Person(2, "yefengyu", "2@qq.com",car);
  7. Person p3 = new Person(3, "yefengyu", "3@qq.com",car);
  8.  
  9. personList.add(p1);
  10. personList.add(p2);
  11. personList.add(p3);
  12.  
  13. System.out.println(JsonSerializer.toJson(personList));
  14. System.out.println(JsonSerializer.toPrettyJson(personList));

结果为:

  1. [{"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"}}]
  2. [ {
  3. "id" : 1,
  4. "name" : "yefengyu",
  5. "email" : "1@qq.com",
  6. "car" : {
  7. "id" : 1,
  8. "brand" : "Rolls-Royce",
  9. "date" : "2019-06-22 13:33:10"
  10. }
  11. }, {
  12. "id" : 2,
  13. "name" : "yefengyu",
  14. "email" : "2@qq.com",
  15. "car" : {
  16. "id" : 1,
  17. "brand" : "Rolls-Royce",
  18. "date" : "2019-06-22 13:33:10"
  19. }
  20. }, {
  21. "id" : 3,
  22. "name" : "yefengyu",
  23. "email" : "3@qq.com",
  24. "car" : {
  25. "id" : 1,
  26. "brand" : "Rolls-Royce",
  27. "date" : "2019-06-22 13:33:10"
  28. }
  29. } ]

3、字符串转为单个对象

  1. String json = "{\"id\":1,\"name\":\"yefengyu\",\"email\":\"110@qq.com\",\"car\":{\"id\":1,\"brand\":\"Rolls-Royce\",\"date\":\"2019-06-22 13:25:30\"}}";
  2. System.out.println(JsonSerializer.fromJson(json, Person.class));

结果如下:

  1. 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、字符串转为对象集合

  1. 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\"}}]";
  1.  
  1. List<Person> persons = JsonSerializer.fromJson(list, new TypeReference<List<Person>>()
  2. {
  3. });
  4.  
  5. for (Person person : persons)
  6. {
  7. System.out.println(person);
  8. }

结果如下:

  1. 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}}
  2. 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}}
  3. 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字符串相互转化的更多相关文章

  1. 使用Google的Gson实现对象和json字符串之间的转换

    使用Google的Gson实现对象和json字符串之间的转换 需要gson.jar 1.JsonUtil.java package com.snail.json; import java.lang.r ...

  2. fastjson: json对象,json对象数组,javabean对象,json字符串之间的相互转化

    fastjson: json对象,json对象数组,javabean对象,json字符串之间的相互转化 在开发过程中,经常需要和前端交互数据,数据交互的格式都是JSON,在此过程中免不了json字符串 ...

  3. JavaScript中JSON对象和JSON字符串的相互转化

    一.JSON字符串转换为JSON对象 var str = '{"name":"cxh","sex":"man",&quo ...

  4. JS中JSON对象和JSON字符串的相互转化

    转:http://www.cnblogs.com/wbyp/p/7086318.html 一.JSON字符串转换为JSON对象 var str = '{"name":"c ...

  5. jQuery中json对象与json字符串互换

    json字符串转json对象:jQuery.parseJSON(jsonStr); json对象转json字符串:JSON.stringify(jsonObj); 根据“|”把字符串变成数组.spli ...

  6. 前端页面使用 Json对象与Json字符串之间的互相转换

    前言 在前端页面很多时候都会用到Json这种格式的数据,最近没有前端,后端的我也要什么都要搞,对于Json对象与Json字符串之间的转换终于摸清楚了几种方式,归纳如下! 一:Json对象转换为json ...

  7. Json对象与Json字符串互转(转载)

    一.jQuery插件支持的转换方式 1 $.paseJSON(jsonstr);//将json字符串转换为json对象 二.浏览器支持的转换方式(Firefox,Chrome,Opera,Safair ...

  8. [TypeScript] TypeScript对象转JSON字符串范例

    [TypeScript] TypeScript对象转JSON字符串范例 Playground http://tinyurl.com/njbrnrv Samples class DataTable { ...

  9. json对象和json字符串有啥区别啊

    json对象可以通过javascript存取属性!json对象装成json字符串经常用于前后台传输数据! 如果你在前台使用,那么Json对象可以通过xx.name来调用,如果是字符串,那么就是字符串了 ...

随机推荐

  1. HDU 6315 Naive Operations 【势能线段树】

    <题目链接> 题目大意: 给出两个序列,a序列全部初始化为0,b序列为输入值.然后有两种操作,add x y就是把a数组[x,y]区间内全部+1,query x y是查询[x,y]区间内∑ ...

  2. 手模手配置Eslint,看懂脚手架中的Eslint

    使用ESLint前:eslint是干嘛的,我这样写有什么问题,怎么还报错了,太麻烦想去掉这个插件,脚手架中关于eslint文件里的配置是什么意思?怎么设置配置项和规则达到自己想要的检测效果呢?怎么集成 ...

  3. Centos上Docker的安装及加速

    #环境 :内核的版本必须大于3.10 #安装docker yum install epel-release -y yum install docker-ce ##安装docker-ce #配置文件 d ...

  4. 微信小程序(5)--阅读器

    最近用微信小程序写了一个图书阅读器,可以实现左右滑动翻页,按钮翻页,上下滚动,切换背景,控制字体大小.以及记住设置好的状态,如页面再次进来保留上次的背景色和字体大小. 由于暂时没有真实的数据接口,所以 ...

  5. 一、小程序内嵌Html示例

    小程序内嵌Html 1.下载wxParse:https://github.com/icindy/wxParse 2.下载完成后将插件目录下的wxParse文件夹拷贝到项目目录下 (文件夹明细) 3.全 ...

  6. setup PC not sleep when turn off display

  7. 描述一下JVM加载class文件的原理机制?

    JVM中类的装载是由类加载器(ClassLoader)和它的子类来实现的,Java中的类加载器是一个重要的Java运行时系统组件,它负责在运行时查找和装入类文件中的类. 由于Java的跨平台性,经过编 ...

  8. JSON 简单例子

    代码: json [ { "title" : "a", "num" : 1 }, { "title" : "b ...

  9. 理解Java构造器中的"this"

    Calling Another Constructor if the first statement of a constructor has the form this(...), then the ...

  10. mui is not defined

    vue项目中引用mui.js,我是在main.js中这样引入的,    结果报错  查找资料,最后在mui.js的最后添加了这样一句  这是因为mui并不能像jquery那样作为全局对象存在,加上wi ...