含有Date和Timestamp的Java和Json互相转化
工程

代码
package com.my.json.helper; import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date; import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
/**
* 将Bean中的Timestamp、Date转换为json中的日期字符串
* @author zhangyi
*
*/
public class DateJsonValueProcessor implements JsonValueProcessor {
public static final String Default_DATE_PATTERN ="yyyy-MM-dd";
private DateFormat dateFormat ;
public DateJsonValueProcessor(String datePattern){
try{
dateFormat = new SimpleDateFormat(datePattern);}
catch(Exception e ){
dateFormat = new SimpleDateFormat(Default_DATE_PATTERN);
}
}
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
return process(value);
}
public Object processObjectValue(String key, Object value,JsonConfig jsonConfig) {
return process(value);
}
private Object process(Object value){
return dateFormat.format((Date)value);
}
}
package com.my.json.helper; import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import net.sf.ezmorph.MorphException;
import net.sf.ezmorph.object.AbstractObjectMorpher; /**
* 将json串中的日期字符串转换为bean中的Timestamp、Date
*
* @author zhangyi
*
*/
public class TimestampMorpher extends AbstractObjectMorpher {
/*** 日期字符串格式 */
private String[] formats; public TimestampMorpher(String[] formats) {
this.formats = formats;
} public Object morph(Object value) {
if (value == null) {
return null;
}
if (Timestamp.class.isAssignableFrom(value.getClass())) {
return (Timestamp) value;
}
if (!supports(value.getClass())) {
throw new MorphException(value.getClass() + " 是不支持的类型");
}
String strValue = (String) value;
SimpleDateFormat dateParser = null;
for (int i = 0; i < formats.length; i++) {
if (null == dateParser) {
dateParser = new SimpleDateFormat(formats[i]);
} else {
dateParser.applyPattern(formats[i]);
}
try {
return new Timestamp(dateParser.parse(strValue.toLowerCase()).getTime());
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
} @Override
public Class morphsTo() {
return Timestamp.class;
} public boolean supports(Class clazz) {
return String.class.isAssignableFrom(clazz);
} }
package com.my.json.helper; import java.sql.Timestamp; import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JSONUtils; public class Util { public static Object jsonToBean(String json,Class cls) {
String[] formats = { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd" };
JSONUtils.getMorpherRegistry().registerMorpher(new TimestampMorpher(formats));
JSONObject jsonObject = JSONObject.fromObject(json);
return JSONObject.toBean(jsonObject, cls);
} public static String beanToJson(Object obj,String dateFormat) {
JsonConfig config = new JsonConfig();
config.registerJsonValueProcessor(Timestamp.class, new DateJsonValueProcessor(dateFormat));
JSONObject json = JSONObject.fromObject(obj, config);
return json.toString();
} }
package com.my.json.helper;
import java.sql.Timestamp;
public class Student {
private int id;
private String name;
private int age;
private Timestamp birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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.my.json.helper;
import java.sql.Timestamp;
public class JsonTest {
public static void main(String[] args) {
Student s = new Student();
s.setId(123456);
s.setName("李四");
s.setAge(20);
Timestamp b = Timestamp.valueOf("1992-10-19 23:52:18");//设置Timestamp、Date类型的值
s.setBirthday(b);
//含有Timestamp、Date的bean转化为Json
String jsonStr = Util.beanToJson(s,"yyyy-MM-dd HH:mm:ss");
System.out.println(jsonStr);
//json转为bean(含有Timestamp、Date)
Student s1 = (Student)Util.jsonToBean(jsonStr,Student.class);
System.out.println(s1.getBirthday().toLocaleString());
}
}
含有Date和Timestamp的Java和Json互相转化的更多相关文章
- 含有Date属性的对象转化为Json
含有Date类型属性的对象,转化为Json,Date属性并不是时间戳格式. 解决方法: 使用Jackson的注解@JsonFormat,添加到对象属性上方即可. 我们的北京时间会相差8个小时,因为我们 ...
- jackson/fastjson、mybatis、mysql date/datatime/timestamp、java Date/Timestamp关系详解
jackson/fastjson序列化/反序列化: 默认情况下,jackson/fastjson将java Date/Timestamp类型序列化为时间戳,也就是1970年1月1日0点以来的毫秒数.如 ...
- JavaBean和json数据之间的转换(二)含有date类型的JavaBean
1.前言 上次讲了简单的JavaBean和json格式之间的转换,代码很简单,但是实际过程中,往往用到的JavaBean都是比较复杂的,其他的字段还好,如果JavaBean中包含了date类型的字段, ...
- Java:String和Date、Timestamp之间的转
Java:String和Date.Timestamp之间的转 一.String与Date(java.util.Date)互转 1.1 String -> Date String dateStr ...
- Java:String和Date、Timestamp之间的转换
一.String与Date(java.util.Date)互转 1.1 String -> Date String dateStr = "2016-9-28 12:25:55" ...
- Spring 整合 Flex (BlazeDS)无法从as对象 到 Java对象转换的异常:org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.util.Date' to required type 'java.sql.Timestamp' for property 'wfsj'; nested exception is java.lang.Ill
异常信息如下: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value ...
- Java含有Date的对象序列化网络传输
与短信接口对接时,Date从我这边传输以及在短信平台接收后转换出了问题 传入一个TemplateRequest对象 Feign接口 将含有Date的将要传输的TemplateRequest加上@Req ...
- [java]String和Date、Timestamp之间的转换
一.String与Date(java.util.Date)互转 1.1 String -> Date Date date = DateFormat.parse(String str); St ...
- Java:String和Date、Timestamp之间的转换【转】
原文地址:http://yunnick.iteye.com/blog/1074495 一.String与Date(java.util.Date)互转 1.1 String -> Date Str ...
随机推荐
- 【洛谷 P1352】没有上司的舞会
树形dp #include<cstdio> #include<cstring> #include<algorithm> using namespace std; ; ...
- SQL Server高级性能调优策略
论坛里经常有人问“我的数据库很慢,有什么办法提高速度呢?”.这是个古老的话题,又是常见的问题,也是DBA们最想解决的问题之一.我想就SQLServer调优大家一起论一论,如果可以的话尽量发表自己观点, ...
- c# XML序列化与反序列化 属性字段标识
序列化对象 public class People { [XmlAttribute("NAME")] public string Name { set; get; } [XmlAt ...
- UITableView表格视图、UITableView代理方法及应用
一.基本知识点 UITableView表格视图,是一个可以滚动的界面(理解为垂直滚动的UIScrollView),可展示多行数据,没有行数的限制,只能有一列. 使用UITableView: 1.展示信 ...
- 安装xubuntu时遇到的一些问题
1 下载地址 http://www.linuxdown.net/ 2 选择虚拟机 VirtualBox 3 安装步骤 http://www.cnblogs.com/zhcncn/p/398730 ...
- IOS笔记之UIKit_UIAlertView、UIActionSheet
//首先必须继承协议 @interface TRViewController : UIViewController<UIAlertViewDelegate,UIActionSheetDelega ...
- .NET 实现自定义ContextUser的Identity和Principal实现自定义用户信息,权限验证。
备用收藏,http://blog.csdn.net/msdnxgh/article/details/6894885 .NET 实现自定义ContextUser的Identity和Principal 在 ...
- Unity3D DF根据名称获取多个子控件代码
dfPanel control = gameObject.GetComponent<dfPanel>(); dfLabel avatarName = control.Find<dfL ...
- 从源代码分析Android-Universal-Image-Loader的缓存处理机制
讲到缓存,平时流水线上的码农一定觉得这是一个高大上的东西.看过网上各种讲缓存原理的文章,总感觉那些文章讲的就是玩具,能用吗?这次我将带你一起看过UIL这个国内外大牛都追捧的图片缓存类库的缓存处理机制. ...
- spring常用jar包总结(转载)
spring.jar是包含有完整发布的单个jar 包,spring.jar中包含除了spring-mock.jar里所包含的内容外其它所有jar包的内容,因为只有在开发环境下才会用到 spring-m ...