JSONObject转换JSON--将Date转换为指定格式
2015-10-22 19:53
513 查看
JSONObject转换JSON--将Date转换为指定格式
博客分类:Java
项目中,经常会用JSONObject插件将JavaBean或List<JavaBean>转换为JSON格式的字符串,而JavaBean的属性有时候会有java.util.Date这个类型的时间对象,这时JSONObject默认会将Date属性转换成这样的格式:
Html代码
![](http://blessht.iteye.com/images/icon_star.png)
{"nanos":0,"time":-27076233600000,"minutes":0,"seconds":0,"hours":0,"month":11,"timezoneOffset":-480,"year":-789,"day":5,"date":22}
而这种格式肯定是非常难以理解的,为了将Date转换为我们认识的“yyyy-MM-dd”格式,需要做以下操作。
首先创建一个时间转换器
Java代码
![](http://blessht.iteye.com/images/icon_star.png)
public class JsonDateValueProcessor implements JsonValueProcessor {
private String format ="yyyy-MM-dd";
public JsonDateValueProcessor() {
super();
}
public JsonDateValueProcessor(String format) {
super();
this.format = format;
}
@Override
public Object processArrayValue(Object paramObject,
JsonConfig paramJsonConfig) {
return process(paramObject);
}
@Override
public Object processObjectValue(String paramString, Object paramObject,
JsonConfig paramJsonConfig) {
return process(paramObject);
}
private Object process(Object value){
if(value instanceof Date){
SimpleDateFormat sdf = new SimpleDateFormat(format,Locale.CHINA);
return sdf.format(value);
}
return value == null ? "" : value.toString();
}
}
然后在调用JSONObject之前创建一个JsonConfig,并且将上一步定义的date转换器注册进去:
Java代码
![](http://blessht.iteye.com/images/icon_star.png)
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
最后将JsonConfig放入JSONObject对象中,这里针对不同的数据类型有多种方式放入JsonConfig:
Java代码
![](http://blessht.iteye.com/images/icon_star.png)
JSONObject json = new JSONObject();
//Map转JSON
json.putAll(Map, jsonConfig);
或者
Java代码
![](http://blessht.iteye.com/images/icon_star.png)
JSONObject json = new JSONObject();
//JavaBean转JSON
json.fromObject(object, jsonConfig)
最后我们看到的结果就是只要JavaBean中有Date对象,转换成JSON字符串时就会变成“yyyy-MM-dd”格式。
相关文章推荐
- JSONObject、JSONArray
- spring mvc配置ObjectMapper忽略无法识别的字段,以及一些博客推荐
- gm: error while loading shared libraries: libpng15.so.15: cannot open shared object file: No such file or directory
- Swift and ObjectiveC Interop (Swift 与 Objective-C 之间的交互)
- Fatal error: Using $this when not in object context in 解决方法
- Objective-C学习-UILabel的使用
- Objective-C 程序设计 第六章
- 【Objective-C学习记录】01-基础概念
- Objective-C编码规范(待补充)
- Objective-C Runtime 运行时之二:成员变量与属性
- Objective-C Runtime 运行时之一:类与对象
- Objective-C Runtime 运行时之三:方法与消息
- objective-C nil,Nil,NULL 和NSNull的小结
- Implicit Object in JSP
- 【IOS开发】objective-c的笔记
- C++STL学习(9)仿函数(function objects, functor)
- Ubuntu下设置外部库(so,shared object)运行环境和ROS中使用外部库编译
- volley JsonObjectRequest 提交参数
- object转json 少参数
- 读effective objective-c 2.0 整理文章 - 11条 理解objc_msgSend的作用