JsonUtil.java
1.66 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
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
81
82
83
84
85
86
package cn.bxe.updatevideo.util;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
import java.util.Map;
/**
 * json工具类
 * @author yonson
 */
public class JsonUtil {
	
	/**
	 * 对像转化为json字符串
	 * @param obj
	 * @return
	 */
	public static String tranObjectToJsonStr(Object obj){
		
		return JSONObject.toJSONString(obj);
		
	}
	
	/**
	 * json字符串转化为对像
	 * @param jsonStr
	 * @return 
	 * @return
	 */
	public static <T extends Object> T tranJsonStrToObject(String jsonStr,Class<T> clazz){
		
		return (T)JSONObject.parseObject(jsonStr,clazz);
		
	}
	
	/**
	 * json字符串转化为列表
	 * @param jsonStr
	 * @param clazz
	 * @return
	 */
	public static <T extends Object> List<T> tranJsonStrToArray(String jsonStr,Class<T> clazz){
		
		return JSONObject.parseArray(jsonStr, clazz);
		
	}
	
	public static JSONObject tranJsonStrToJSONObject(String jsonStr){
		return JSONObject.parseObject(jsonStr);
	}
	public static Map tranJsonToMap(String jsonStr){
		try {
			Map mapObj = JSONObject.parseObject(jsonStr, Map.class);
			//for (Object map: mapObj.entrySet()){
			//	System.out.println(((Map.Entry)map).getKey()+"  "+((Map.Entry)map).getValue());
			//}
			return mapObj;
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}
	/**
	 *
	 * @param jsonStr
	 * @param keyField
	 * @return
	 */
	public static String tranJsonToMapAndGetKValue(String jsonStr,String keyField){
		try {
			Map mapObj = tranJsonToMap(jsonStr);
			if(mapObj!=null && mapObj.containsKey(keyField)) {
				return String.valueOf(mapObj.get(keyField));
			}
			else
				return "";
		}catch (Exception e){
			e.printStackTrace();
		}
		return "";
	}
}