先定义实体类:

package com.zf.vo; import java.sql.Timestamp; import
com.fasterxml.jackson.annotation.JsonIgnore; import
com.fasterxml.jackson.databind.annotation.JsonSerialize; import
com.zf.control.JsonTimestampFormater; public class Person { private String name
; @JsonIgnore //表示将该对象转换为json String的时候,忽略该属性 private int age ;
@JsonSerialize(using = JsonTimestampFormater.class)
//表示将该对象转换为Json对象的时候,使用的类型转器为自己定义的转换器 private Timestamp birthday ; 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 Timestamp getBirthday() { return birthday; } public
void setBirthday(Timestamp birthday) { this.birthday = birthday; } }

类型转换器定义如下:

package com.zf.control; import java.io.IOException; import java.sql.Timestamp;
import java.text.SimpleDateFormat; import
com.fasterxml.jackson.core.JsonGenerator; import
com.fasterxml.jackson.core.JsonProcessingException; import
com.fasterxml.jackson.databind.JsonSerializer; import
com.fasterxml.jackson.databind.SerializerProvider; public class
JsonTimestampFormater extends JsonSerializer<Timestamp> { private final
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); @Override
public void serialize(Timestamp value, JsonGenerator jgen, SerializerProvider
sp) throws IOException, JsonProcessingException {
jgen.writeString(sdf.format(value)); } }

测试类如下:

package com.zf.test; import java.io.IOException; import java.sql.Timestamp;
import com.fasterxml.jackson.core.JsonGenerationException; import
com.fasterxml.jackson.databind.JsonMappingException; import
com.fasterxml.jackson.databind.ObjectMapper; import com.zf.vo.Person; public
class Test { public static void main(String[] args) throws
JsonGenerationException, JsonMappingException, IOException { Person person =
new Person(); person.setAge(19); person.setName("xxxxx");
person.setBirthday(new Timestamp(System.currentTimeMillis())); ObjectMapper
mapper = new ObjectMapper(); String jsonstr =
mapper.writeValueAsString(person); System.out.println(jsonstr); } }

打印结果

{"name":"xxxxx","birthday":"2012-08-03 03:05:06"}

技术
©2020 ioDraw All rights reserved
程序员升职记第28关三排序代码使用ADB命令卸载安卓设备上的应用centos7部署springboot jar包网上赚钱的门路方法,大部分人都是利用这三种方法!每周计划思维导图模板mac解决Enter passphrase for key每次输入密码PHP 先返回结果到前端,PHP代码继续执行后续的任务MariaDB数据库用户创建/删除及权限授权/撤回Docker容器和镜像的导入、导出天猫等网店要挟用户成风?要硬钢!别惯他们臭毛病