当前位置: 代码迷 >> JavaScript >> date门类json字符串的内部替换
  详细解决方案

date门类json字符串的内部替换

热度:277   发布时间:2013-08-16 14:29:57.0
date类型json字符串的内部替换

用json格式传输内容有很多好处,但是如果遇到像页面传输时间类型的,就有麻烦了。一般要求时间格式YYYY-MM-DD的,但是到页面上却是一个对象(【object,object】)。查看到页面上的json字符串确是

String json1={"id":5,"birthday":{"nanos":0,"time":1179676800000,"minutes":0,"seconds":0,"hours":0,"month":4,"year":107,"timezoneOffset":-480,"day":1,"date":21},"phone":"32321","email":"232@qq.com","name":"213","age":-2147483648,"workage":-2147483648,"gender":0,"entrytime":{"nanos":0,"time":1306080000000,"minutes":0,"seconds":0,"hours":0,"month":4,"year":111,"timezoneOffset":-480,"day":1,"date":23},"qq":"32321323232"}
大家可以看到birthday已经被封装成这个样子了,"birthday":{"nanos":0,"time":1179676800000,"minutes":0,"seconds":0,"hours":0,"month":4,"year":107,"timezoneOffset":-480,"day":1,"date":21},",所以可以在生产这个json串之前单独取出来,并进行相应的格式化成字符串:

String entrytime=DateFormatUtil.formatDate(company_content.getEntrytime());
String birthday=DateFormatUtil.formatDate(company_content.getBirthday());

?

成为YYYY-MM-DD类型的,再把json1中的birthday所对应的value替换掉即可。

String jsonStr2=JSONObject.fromObject(company_content).toString();//原来的json串
JSONObject jsonObject=JSONObject.fromObject(jsonStr2);生成新的json对象
???/**
??? * 替换json串
??? */
???jsonObject.put("entrytime", entrytime);//将原来json串中的entrytime中的value替换成自己格式化好的时间
???jsonObject.put("birthday", birthday);
???System.out.println("!!!!!!!"+jsonObject);
???
???response.getWriter().write(jsonObject.toString());

新的json串是:

{"id":5,"birthday":"2007-05-21","phone":"32321","email":"232@qq.com","age":-2147483648,"name":"213","workage":-2147483648,"entrytime":"2011-05-23","gender":0,"qq":"32321323232"}

这样birthday里面的内容就完全转换过来了,就可以打印到页面上去了。

注:jsonObject.get(key);可以得到某个json串里面某个value值,通过key值。

  相关解决方案