您的位置:首页 > 编程语言 > Java开发

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

2014-03-19 20:06 525 查看
转载自:http://www.yuuzle.com/java-and-json-conversion-to-resolve-the-question-of-the-date.html

JSON即JavaScript
ObjectNatation,它是一种轻量级的数据交换格式,非常适合于服务器与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-》JSON

1.List-》JSON

1
List<String>
list=
new

ArrayList<String>();
2
list.add(
"apple"
);
3
list.add(
"orange"
);
4
JSONArray
jarr=JSONArray.fromObject(list);
5
System.out.println(
"list->json:"

+jarr.toString());
打印结果:list->json:["apple","orange"]

2.Map-》JSON

1
Map<String,
Object>map=
new

HashMap<String,Object>();
2
map.put(
"name"
,
"Michael"
);
3
map.put(
"baby"
,
new

String[]{
"Lucy"
,
"Lily"

});
4
map.put(
"age"
,
30
);
5
JSONObject
jo=JSONObject.fromObject(map);
6
System.out.println(
"map->json:"

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

1
JsonBean
bean=
new

JsonBean();
2
bean.setName(
"NewBaby"
);
3
bean.setAge(
1
);
4
bean.setBorn(
new

Date());
5
jo
=JSONObject.fromObject(bean);
6
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"}4.bean->JSON日期转换

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

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

1
/**
2
*
JSON日期格式处理(java转化为JSON)
3
*
@authorMichaelsun
4
*/
5
public

class

JsonDateValueProcessor
implements


JsonValueProcessor{
6
7
/**
8
*
datePattern
9
*/
10
private


StringdatePattern=
"yyyy-MM-dd"
;
11
12
/**
13
*
JsonDateValueProcessor
14
*/
15
public


JsonDateValueProcessor(){
16
super
();
17
}
18
19
/**
20
*
@paramformat
21
*/
22
public


JsonDateValueProcessor(Stringformat){
23
super
();
24
this
.datePattern
=format;
25
}
26
27
/**
28
*
@paramvalue
29
*
@paramjsonConfig
30
*
@returnObject
31
*/
32
public


ObjectprocessArrayValue(Objectvalue,JsonConfigjsonConfig){
33
return


process(value);
34
}
35
36
/**
37
*
@paramkey
38
*
@paramvalue
39
*
@paramjsonConfig
40
*
@returnObject
41
*/
42
public


ObjectprocessObjectValue(Stringkey,Objectvalue,
43
JsonConfig
jsonConfig){
44
return


process(value);
45
}
46
47
/**
48
*
process
49
*
@paramvalue
50
*
@return
51
*/
52
private


Objectprocess(Objectvalue){
53
try


{
54
if

(value
instanceof


Date){
55
SimpleDateFormat
sdf=
new


SimpleDateFormat(datePattern,
56
Locale.UK);
57
return


sdf.format((Date)value);
58
}
59
return


value==
null


?
""


:value.toString();
60
}
catch

(Exceptione){
61
return

""
;
62
}
63
64
}
65
66
/**
67
*
@returnthedatePattern
68
*/
69
public


StringgetDatePattern(){
70
return


datePattern;
71
}
72
73
/**
74
*
@parampDatePatternthedatePatterntoset
75
*/
76
public

void

setDatePattern(StringpDatePattern){
77
datePattern
=pDatePattern;
78
}
79
80
}
测试代码:

1
JsonBean
bean=
new

JsonBean();
2
bean.setName(
"NewBaby"
);
3
bean.setAge(
1
);
4
bean.setBorn(
new

Date());
5
6
JsonConfig
jsonConfig=
new


JsonConfig();
7
jsonConfig.registerJsonValueProcessor(Date.
class
,
8
new


JsonDateValueProcessor());
9
10
JSONObject
jo=JSONObject.fromObject(bean,jsonConfig);
11
System.out.println(
"bean->json:"

+jo.toString());
打印结果:bean->json:{"age":1,"born":"2010-03-10","name":"NewBaby"}这就能得到我们想要的结果了。

4.java->JSON过滤指定的属性

1
JsonBean
bean=
new

JsonBean();
2
bean.setName(
"NewBaby"
);
3
bean.setAge(
1
);
4
bean.setBorn(
new

Date());
5
jo
=JSONObject.fromObject(bean);
6
7
JsonConfig
jsonConfig=
new


JsonConfig();
8
9
PropertyFilter
filter=
new


PropertyFilter(){
10
public

boolean

apply(Objectsource,Stringname,Objectvalue){
11
if

(
"born"
.equals(name))
{
12
return

true
;
13
}
14
return

false
;
15
}
16
};
17
jsonConfig.setJsonPropertyFilter(filter);
18
19
njo
=JSONObject.fromObject(bean,jsonConfig);
20
System.out.println(
"bean->json
[addpropertyfilter]:"
21
+njo.toString());
打印结果:bean->json[addpropertyfilter]:{"age":1,"name":"NewBaby"}从执行结果可以看出:born这个属性已经成功过滤掉了。

三、JSON-》java

1.如何把json的yyyy-MM-dd的转换为Bean中的util.Date类型:

1
JSONUtils.getMorpherRegistry().registerMorpher(
2
new

DateMorpher(
new

String[]{
"yyyy-MM-dd"


}));
3
4
String
jsonStr=
"[{\"name\":
\"husband\",\"age\":\"26\",\"born\":\"1984-01-12\"},{\"name\":\"wife\",\"age\":\"20\",\"born\":\"1990-05-01\"}]"
;
5
6
Collection<JsonBean>list=JSONArray.toCollection(JSONArray
7
.fromObject(jsonStr),JsonBean.
class
);
8
//DateUtil.getFormatDate(date,fmtstr)日期转字符串这里不再写代码了
9
for

(JsonBeano:list){
10
System.out.println(DateUtil
11
.getFormatDate(o.getBorn(),
"yyyy-MM-dd"
));
12
}
打印结果:

1984-01-12

1990-05-01

2.JSON-》List、Map

1
String
listStr=
"[\"apple\",\"orange\"]"
;
2
Collection<String>strlist=JSONArray.toCollection(JSONArray
3
.fromObject(listStr));
4
for

(Stringstr:strlist){
5
System.out.println(str);
6
}
7
8
String
mapStr=
"{\"age\":30,\"name\":\"Michael\",\"baby\":[\"Lucy\",\"Lily\"]}"
;
9
Map<String,
Object>map=(Map)JSONObject.toBean(JSONObject
10
.fromObject(mapStr),Map.
class
);
11
for

(Entry<String,Object>entry:map.entrySet()){
12
System.out.println(entry.getKey()
+
"
"

+entry.getValue());
13
}
打印结果:

apple

orange

nameMichael

age30

baby[Lucy,Lily]

返回
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐