java jsonobject 日期_java与json互相转换(解决日期问题)

JSON 即 JavaScript Object Natation,它是一种轻量级的数据交换格式,非常适合于服务器与 JavaScript 的交互。本文主要讲解下java和JSON之间的转换,特别是解决互相转换遇到日期问题的情况。

一、需要相关的jar包:

json-lib-xxx.jar

ezmorph-xxx.jar

commons-httpclient-xxx.jar

commons-lang-xxx.jar

commons-logging-xxx.jar

commons-collections-xxx.jar

上面的包可以从下面的连接下载:

http://commons.apache.org/index.html

http://json-lib.sourceforge.net

http://ezmorph.sourceforge.net

二、java-》JSON1.List-》JSON

view plaincopy to clipboardprint?List list = new ArrayList();

list.add("apple");

list.add("orange");

JSONArray jarr=JSONArray.fromObject(list);

System.out.println("list->json:" +jarr.toString());

打印结果:list->json:["apple","orange"]2.Map-》JSON

view plaincopy to clipboardprint?Map map = new HashMap();

map.put("name", "Michael");

map.put("baby", new String[] { "Lucy", "Lily"});

map.put("age", 30);

JSONObject jo=JSONObject.fromObject(map);

System.out.println("map->json:" +jo.toString());

打印结果:map->json:{"age":30,"name":"Michael","baby":["Lucy","Lily"]}3.bean->JSON

view plaincopy to clipboardprint?JsonBean bean= newJsonBean();

bean.setName("NewBaby");

bean.setAge(1);

bean.setBorn(newDate());

jo=JSONObject.fromObject(bean);

System.out.println("bean->json:" +jo.toString());

打印结果:bean->json:{"age":1,"born":{"date":10,"day":3,"hours":14,"minutes":14,"month":2,"seconds":1,"time":1268201641228,"timezoneOffset":-480,"year":110},"name":"NewBaby"}

这时你会发现它把bean对象里的util.Date这个类型的所有属性一一转换出来。在实际运用过程中,大多数情况下我们希望能转化为yyyy-MM-dd这种格式,下面就讲一讲如何实现:

首先要写一个新的类JsonDateValueProcessor如下:

view plaincopy to clipboardprint?

/*** JSON 日期格式处理(java转化为JSON)

*@authorMichael sun*/

public class JsonDateValueProcessor implementsJsonValueProcessor {/*** datePattern*/

private String datePattern = "yyyy-MM-dd";/*** JsonDateValueProcessor*/

publicJsonDateValueProcessor() {super();

}/***@paramformat*/

publicJsonDateValueProcessor(String format) {super();this.datePattern =format;

}/***@paramvalue

*@paramjsonConfig

*@returnObject*/

publicObject processArrayValue(Object value, JsonConfig jsonConfig) {returnprocess(value);

}/***@paramkey

*@paramvalue

*@paramjsonConfig

*@returnObject*/

publicObject processObjectValue(String key, Object value,

JsonConfig jsonConfig) {returnprocess(value);

}/*** process

*@paramvalue

*@return

*/

privateObject process(Object value) {try{if (value instanceofDate) {

SimpleDateFormat sdf= newSimpleDateFormat(datePattern,

Locale.UK);returnsdf.format((Date) value);

}return value == null ? "": value.toString();

}catch(Exception e) {return "";

}

}/***@returnthe datePattern*/

publicString getDatePattern() {returndatePattern;

}/***@parampDatePattern the datePattern to set*/

public voidsetDatePattern(String pDatePattern) {

datePattern=pDatePattern;

}

}

测试代码:

view plaincopy to clipboardprint?JsonBean bean= newJsonBean();

bean.setName("NewBaby");

bean.setAge(1);

bean.setBorn(newDate());

JsonConfig jsonConfig= newJsonConfig();

jsonConfig.registerJsonValueProcessor(Date.class,newJsonDateValueProcessor());

JSONObject jo=JSONObject.fromObject(bean, jsonConfig);

System.out.println("bean->json:" +jo.toString());

打印结果:bean->json:{"age":1,"born":"2010-03-10","name":"NewBaby"}

这就能得到我们想要的结果了。

三、JSON-》java1.如何把json的yyyy-MM-dd的转换为Bean中的util.Date类型:

view plaincopy to clipboardprint?JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] { "yyyy-MM-dd"}));

String jsonStr= "[{\"name\": \"husband\", \"age\": \"26\", \"born\": \"1984-01-12\"},{\"name\": \"wife\", \"age\": \"20\", \"born\": \"1990-05-01\"}]";

Collection list = JSONArray.toCollection(JSONArray.fromObject(jsonStr), JsonBean.class);//DateUtil.getFormatDate(date,fmtstr)日期转字符串这里不再写代码了

for(JsonBean o : list) {

System.out.println(DateUtil.getFormatDate(o.getBorn(),"yyyy-MM-dd"));

}

打印结果:1984-01-12

1990-05-01

2. JSON-》List、 Map

view plaincopy to clipboardprint?String listStr= "[\"apple\",\"orange\"]";

Collection strlist =JSONArray.toCollection(JSONArray.fromObject(listStr));for(String str : strlist) {

System.out.println(str);

}

String mapStr= "{\"age\":30,\"name\":\"Michael\",\"baby\":[\"Lucy\",\"Lily\"]}";

Map map =(Map) JSONObject.toBean(JSONObject

.fromObject(mapStr), Map.class);for (Entryentry : map.entrySet()) {

System.out.println(entry.getKey()+ " " +entry.getValue());

}

打印结果:

apple

orange

name Michael

age30baby [Lucy, Lily]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值