分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

【json】Jackson的使用

发布时间:2023-09-06 01:51责任编辑:白小东关键词:jsjson

Jackson所有的操作都是通过ObjectMapper对象实例来操作的,可以重用这个对象实例。

首先定义一个实例:
ObjectMapper mapper = new ObjectMapper();

定义一个Student类:

 ???package jackson; ???import java.util.Date; ???public class Student { ???????private String name; ???????private int age; ???????private String position; ???????private Date createTime; ???????public String getName() { ???????????return name; ???????} ???????public void setName(String name) { ???????????this.name = name; ???????} ???????public int getAge() { ???????????return age; ???????} ???????public void setAge(int age) { ???????????this.age = age; ???????} ???????public String getPosition() { ???????????return position; ???????} ???????public void setPosition(String position) { ???????????this.position = position; ???????} ???????public Date getCreateTime() { ???????????return createTime; ???????} ???????public void setCreateTime(Date createTime) { ???????????this.createTime = createTime; ???????} ???????@Override ???????public String toString() { ???????????return "Student [name=" + name + ", age=" + age + ", position=" ???????????????????+ position + ", createTime=" + createTime + "]"; ???????} ???}

准备一个字符串:
String jsonString = "{\"name\":\"king\",\"age\":21}";

常规操作: 字符串转对象

 ????mapper.readValue(jsonString,Student.class); ????System.out.println(student);

打印输出结果:

Student [name=king, age=21, position=null, createTime=null]

常规操作: 对象转字符串

 ???????student.setCreateTime(new Date()); ???????String json = mapper.writeValueAsString(student); ???????System.out.println(json);

打印输出结果:

{"name":"king","age":21,"position":null,"createTime":1524819355361}

如何改变输出的日期字段格式?

两种方式:一种SimpleDateFormat,另外一种通过在属性字段注解
在Student.java属性字段createTime注解@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")

import com.fasterxml.jackson.annotation.JsonFormat;public class Student { ???private String name; ???private int age; ???private String position; ???@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") ?????private Date createTime; ????????????//省略get,set}

打印输出结果:

{"name":"king","age":21,"position":null,"createTime":"2018-04-27 09:00:56"}

8小时时间差问题:上面打印结果发现,时间少8小时。

解决方法: 注解上增加时区。

public class Student { ???private String name; ???private int age; ???private String position; ???@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") ?????private Date createTime; ???????????????//省略get,set}

打印输出结果:

{"name":"king","age":21,"position":null,"createTime":"2018-04-27 17:07:33"}

【json】Jackson的使用

原文地址:https://www.cnblogs.com/30go/p/8963290.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved