-
Notifications
You must be signed in to change notification settings - Fork 269
/
GsonUtil.java
114 lines (103 loc) · 2.68 KB
/
GsonUtil.java
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package com.example.utils;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @创建者 Blizzard-liu
* @创建时间 2017/5/9 11:04
* @描述 ${TODO}
* @更新者 ${Author}
* @更新时间 2017/5/9
* @更新描述 ${compile 'com.google.code.gson:gson:2.2.4'}
*/
public class GsonUtil {
/**
* 把一个map变成json字符串
* @param map
* @return
*/
public static String parseMapToJson(Map<?, ?> map) {
try {
Gson gson = new Gson();
return gson.toJson(map);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 把一个json字符串变成对象
* @param json
* @param cls
* @return
*/
public static <T> T parseJsonToBean(String json, Class<T> cls) {
Gson gson = new Gson();
T t = null;
try {
t = gson.fromJson(json, cls);
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
/**
* 把json字符串变成map
* @param json
* @return
*/
public static HashMap<String, Object> parseJsonToMap(String json) {
Gson gson = new Gson();
Type type = new TypeToken<HashMap<String, Object>>() {
}.getType();
HashMap<String, Object> map = null;
try {
map = gson.fromJson(json, type);
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
/**
* 把json字符串变成集合
* params: new TypeToken<List<yourbean>>(){}.getType(),
*
* @param json
* @param type new TypeToken<List<yourbean>>(){}.getType()
* @return
*/
public static List<?> parseJsonToList(String json, Type type) {
Gson gson = new Gson();
List<?> list = gson.fromJson(json, type);
return list;
}
/**
*
* 获取json串中某个字段的值,注意,只能获取同一层级的value
*
* @param json
* @param key
* @return
*/
public static String getFieldValue(String json, String key) {
if (TextUtils.isEmpty(json))
return null;
if (!json.contains(key))
return "";
JSONObject jsonObject = null;
String value = null;
try {
jsonObject = new JSONObject(json);
value = jsonObject.getString(key);
} catch (JSONException e) {
e.printStackTrace();
}
return value;
}
}