JSONUtil.java
1.21 KB
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
package com.sitech.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
*
* @author liujhc
*/
public class JSONUtil {
/**
* 将java对象转换成json字符串
* @param obj
* @return
*/
public static String toJSON(Object obj) {
if (obj == null) {
return null;
} else if (obj.getClass().isArray() || obj instanceof Collection) {
return JSONArray.fromObject(obj).toString();
} else {
return JSONObject.fromObject(obj).toString();
}
}
/**
* 将json字符串数组转换成java的List对象,对象转换成java的Map对象
* @param json
* @return
*/
public static Object fromJSON(String json){
if (json == null) {
return null;
} else if (json.startsWith("[")) {
return JSONArray.fromObject(json);
} else {
return JSONObject.fromObject(json);
}
}
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("aa");
list.add("bb");
System.out.println(JSONUtil.toJSON(list));
}
}