01
02
03
04
05
06
|
public
Map<String,Object> parseJson(String json){
GsonBuilder gsonBuilder =
new
GsonBuilder();
gsonBuilder.registerTypeAdapter(Object.
class
,
new
NaturalDeserializer());
Gson gson = gsonBuilder.create();
return
gson.fromJson(json, HashMap.
class
);
}
|
01
02
03
04
05
06
07
08
09
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
|
/**
* 解析 服务器返回的json时使用的解析器
* @author feicien
*
*/
public
class
NaturalDeserializer
implements
JsonDeserializer<Object> {
@Override
public
Object deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws
JsonParseException {
if
(json.isJsonNull()) {
return
null
;
}
else
if
(json.isJsonPrimitive()) {
return
handlePrimitive(json.getAsJsonPrimitive());
}
else
if
(json.isJsonArray()) {
return
handleArray(json.getAsJsonArray(), context);
}
else
{
return
handleObject(json.getAsJsonObject(), context);
}
}
private
Object handleObject(JsonObject json,
JsonDeserializationContext context) {
Map<String, Object> map =
new
HashMap<String, Object>();
for
(Map.Entry<String, JsonElement> entry : json.entrySet())
map.put(entry.getKey(),
context.deserialize(entry.getValue(), Object.
class
));
return
map;
}
private
Object handleArray(JsonArray json,
JsonDeserializationContext context) {
List<Object> array =
new
ArrayList<Object>();
int
length = json.size();
for
(
int
i =
0
; i < length; i++) {
array.add(context.deserialize(json.get(i), Object.
class
));
}
return
array;
}
private
Object handlePrimitive(JsonPrimitive json) {
if
(json.isBoolean())
return
json.getAsBoolean();
else
if
(json.isString())
return
json.getAsString();
else
{
BigDecimal bigDec = json.getAsBigDecimal();
// Find out if it is an int type
try
{
bigDec.toBigIntegerExact();
try
{
return
bigDec.intValueExact();
}
catch
(ArithmeticException e) {
}
return
bigDec.longValue();
}
catch
(ArithmeticException e) {
}
// Just return it as a double
return
bigDec.doubleValue();
}
}
}
|