JsonKit.java
1.4 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
package com.framework.util;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
/**
* Depiction:
* <p>
* Modify:
* <p>
* Author: Kevin Lynn
* <p>
* Create Date:2018年4月23日 下午6:48:25
*
*/
public class JsonKit {
public JsonKit() {
}
/**
* Json数据解析
*
* @param <T>
* @param json
* json源串
* @return List<T>
*/
public static <T> List<T> parseArray(String json, Class<T> type) {
List<T> list = new ArrayList<T>();
try {
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray jsonarray = parser.parse(json).getAsJsonArray();
for (JsonElement element : jsonarray) {
list.add(gson.fromJson(element, type));
}
} catch (Exception e) {
System.err.println("JsonKit parseArray()" + e.toString());
System.err.println();
}
return list;
}
/**
* Json数据解析
*
* @param json
* json源串
* @param cls
* 存储json的实体类
* @return 相应的实体类对象
*/
public static <T> T parseJson(String json, Type cls) {
try {
Gson gson = new Gson();
return gson.fromJson(json, cls);
} catch (Exception e) {
System.err.println(cls.getClass().getSimpleName() + " parseJson()" + e.toString());
System.err.println();
}
return null;
}
}