JSON 即 http://commons.apache.org/index.html
http://json-lib.sourceforge.net
http://ezmorph.sourceforge.net
二、java-》JSON
1.List-》JSON
List<String> list = new ArrayList<String>();
list.add("apple");
list.add("orange");
JSONArray jarr = JSONArray.fromObject(list);
System.out.println("list->json:" + jarr.toString());
1
2
3
4
5
List<String>list=newArrayList<String>();
list.add("apple");
list.add("orange");
JSONArrayjarr=JSONArray.fromObject(list);
System.out.println("list->json:"+jarr.toString());
打印结果:list->json:[“apple”,”orange”]
2.Map-》JSON
Map<String, Object> map = new HashMap<String, Object>();
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());
1
2
3
4
5
6
Map<String,Object>map=newHashMap<String,Object>();
map.put("name","Michael");
map.put("baby",newString[]{"Lucy","Lily"});
map.put("age",30);
JSONObjectjo=JSONObject.fromObject(map);
System.out.println("map->json:"+jo.toString());
打印结果:map->json:{“age”:30,”name”:”Michael”,”baby”:[“Lucy”,”Lily”]}
3.bean->JSON
JsonBean bean = new JsonBean();
bean.setName("NewBaby");
bean.setAge(1);
bean.setBorn(new Date());
jo = JSONObject.fromObject(bean);
System.out.println("bean->json:" + jo.toString());
1
2
3
4
5
6
JsonBeanbean=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”}
4.bean->JSON 日期转换
上面的例子中你会发现它把bean对象里的util.Date这个类型的所有属性一一转换出来。在实际运用过程中,大多数情况下我们希望能转化为yyyy-MM-dd这种格式,下面就讲一讲如何实现:
首先要写一个新的类JsonDateValueProcessor如下:
/**
* JSON 日期格式处理(java转化为JSON)
* @author Michael sun
*/
public class JsonDateValueProcessor implements JsonValueProcessor {
/**
* datePattern
*/
private String datePattern = "yyyy-MM-dd";
/**
* JsonDateValueProcessor
*/
public JsonDateValueProcessor() {
super();
}
/**
* @param format
*/
public JsonDateValueProcessor(String format) {
super();
this.datePattern = format;
}
/**
* @param value
* @param jsonConfig
* @return Object
*/
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
return process(value);
}
/**
* @param key
* @param value
* @param jsonConfig
* @return Object
*/
public Object processObjectValue(String key, Object value,
JsonConfig jsonConfig) {
return process(value);
}
/**
* process
* @param value
* @return
*/
private Object process(Object value) {
try {
if (value instanceof Date) {
SimpleDateFormat sdf = new SimpleDateFormat(datePattern,
Locale.UK);
return sdf.format((Date) value);
}
return value == null ? "" : value.toString();
} catch (Exception e) {
return "";
}
}
/**
* @return the datePattern
*/
public String getDatePattern() {
return datePattern;
}
/**
* @param pDatePattern the datePattern to set
*/
public void setDatePattern(String pDatePattern) {
datePattern = pDatePattern;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* JSON 日期格式处理(java转化为JSON)
* @author Michael sun
*/
publicclassJsonDateValueProcessorimplementsJsonValueProcessor{
/**
* datePattern
*/
privateStringdatePattern="yyyy-MM-dd";
/**
* JsonDateValueProcessor
*/
publicJsonDateValueProcessor(){
super();
}
/**
* @param format
*/
publicJsonDateValueProcessor(Stringformat){
super();
this.datePattern=format;
}
/**
* @param value
* @param jsonConfig
* @return Object
*/
publicObjectprocessArrayValue(Objectvalue,JsonConfigjsonConfig){
returnprocess(value);
}
/**
* @param key
* @param value
* @param jsonConfig
* @return Object
*/
publicObjectprocessObjectValue(Stringkey,Objectvalue,
JsonConfigjsonConfig){
returnprocess(value);
}
/**
* process
* @param value
* @return
*/
privateObjectprocess(Objectvalue){
try{
if(valueinstanceofDate){
SimpleDateFormatsdf=newSimpleDateFormat(datePattern,
Locale.UK);
returnsdf.format((Date)value);
}
returnvalue==null?"":value.toString();
}catch(Exceptione){
return"";
}
}
/**
* @return the datePattern
*/
publicStringgetDatePattern(){
returndatePattern;
}
/**
* @param pDatePattern the datePattern to set
*/
publicvoidsetDatePattern(StringpDatePattern){
datePattern=pDatePattern;
}
}
测试代码:
JsonBean bean = new JsonBean();
bean.setName("NewBaby");
bean.setAge(1);
bean.setBorn(new Date());
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class,
new JsonDateValueProcessor());
JSONObject jo = JSONObject.fromObject(bean, jsonConfig);
System.out.println("bean->json:" + jo.toString());
1
2
3
4
5
6
7
8
9
10
11
JsonBeanbean=newJsonBean();
bean.setName("NewBaby");
bean.setAge(1);
bean.setBorn(newDate());
JsonConfigjsonConfig=newJsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class,
newJsonDateValueProcessor());
JSONObjectjo=JSONObject.fromObject(bean,jsonConfig);
System.out.println("bean->json:"+jo.toString());
打印结果:bean->json:{“age”:1,”born”:”2010-03-10″,”name”:”NewBaby”}
这就能得到我们想要的结果了。
4.java->JSON 过滤指定的属性
JsonBean bean = new JsonBean();
bean.setName("NewBaby");
bean.setAge(1);
bean.setBorn(new Date());
jo = JSONObject.fromObject(bean);
JsonConfig jsonConfig = new JsonConfig();
PropertyFilter filter = new PropertyFilter() {
public boolean apply(Object source, String name, Object value) {
if ("born".equals(name)) {
return true;
}
return false;
}
};
jsonConfig.setJsonPropertyFilter(filter);
njo = JSONObject.fromObject(bean, jsonConfig);
System.out.println("bean->json [add property filter] :"
+ njo.toString());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
JsonBeanbean=newJsonBean();
bean.setName("NewBaby");
bean.setAge(1);
bean.setBorn(newDate());
jo=JSONObject.fromObject(bean);
JsonConfigjsonConfig=newJsonConfig();
PropertyFilterfilter=newPropertyFilter(){
publicbooleanapply(Objectsource,Stringname,Objectvalue){
if("born".equals(name)){
returntrue;
}
returnfalse;
}
};
jsonConfig.setJsonPropertyFilter(filter);
njo=JSONObject.fromObject(bean,jsonConfig);
System.out.println("bean->json[addpropertyfilter]:"
+njo.toString());
打印结果:bean->json [add property filter] :{“age”:1,”name”:”NewBaby”}
从执行结果可以看出:born 这个属性已经成功过滤掉了。
三、JSON-》java
1.如何把json的yyyy-MM-dd的转换为Bean中的util.Date类型:
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<JsonBean> 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"));
}
1
2
3
4
5
6
7
8
9
10
11
12
JSONUtils.getMorpherRegistry().registerMorpher(
newDateMorpher(newString[]{"yyyy-MM-dd"}));
StringjsonStr="[{\"name\":\"husband\",\"age\":\"26\",\"born\":\"1984-01-12\"},{\"name\":\"wife\",\"age\":\"20\",\"born\":\"1990-05-01\"}]";
Collection<JsonBean>list=JSONArray.toCollection(JSONArray
.fromObject(jsonStr),JsonBean.class);
//DateUtil.getFormatDate(date,fmtstr)日期转字符串这里不再写代码了
for(JsonBeano:list){
System.out.println(DateUtil
.getFormatDate(o.getBorn(),"yyyy-MM-dd"));
}
打印结果:
1984-01-12
1990-05-01
2. JSON-》List、 Map
String listStr = "[\"apple\",\"orange\"]";
Collection<String> strlist = JSONArray.toCollection(JSONArray
.fromObject(listStr));
for (String str : strlist) {
System.out.println(str);
}
String mapStr = "{\"age\":30,\"name\":\"Michael\",\"baby\":[\"Lucy\",\"Lily\"]}";
Map<String, Object> map = (Map) JSONObject.toBean(JSONObject
.fromObject(mapStr), Map.class);
for (Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
1
2
3
4
5
6
7
8
9
10
11
12
13
StringlistStr="[\"apple\",\"orange\"]";
Collection<String>strlist=JSONArray.toCollection(JSONArray
.fromObject(listStr));
for(Stringstr:strlist){
System.out.println(str);
}
StringmapStr="{\"age\":30,\"name\":\"Michael\",\"baby\":[\"Lucy\",\"Lily\"]}";
Map<String,Object>map=(Map)JSONObject.toBean(JSONObject
.fromObject(mapStr),Map.class);
for(Entry<String,Object>entry:map.entrySet()){
System.out.println(entry.getKey()+""+entry.getValue());
}
打印结果:
apple
orange
name Michael
age 30
baby [Lucy, Lily]