Skip to content

Commit e37e9f9

Browse files
committed
Add JsonUtils
1 parent 508b01a commit e37e9f9

File tree

1 file changed

+56
-0
lines changed
  • src/AndroidClient/client/src/main/java/net/servicestack/client

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package net.servicestack.client;
2+
3+
import com.google.gson.JsonElement;
4+
import com.google.gson.JsonObject;
5+
import com.google.gson.JsonParser;
6+
7+
import java.util.HashMap;
8+
import java.util.Map;
9+
10+
/**
11+
* Created by mythz on 2/10/2017.
12+
*/
13+
14+
public class JsonUtils {
15+
16+
public static JsonObject toJsonObject(String json) {
17+
JsonElement e = new JsonParser().parse(json);
18+
if (e.isJsonObject()) {
19+
return e.getAsJsonObject();
20+
}
21+
return null;
22+
}
23+
24+
public static String asString(JsonObject obj, String key) {
25+
if (obj == null)
26+
return null;
27+
if (key == null)
28+
throw new IllegalArgumentException("key is null");
29+
30+
return asString(obj.get(key));
31+
}
32+
33+
public static String asString(JsonElement el)
34+
{
35+
return el != null
36+
? el.getAsString()
37+
: null;
38+
}
39+
40+
public static long asLong(JsonObject obj, String key) {
41+
return asLong(obj, key, 0);
42+
}
43+
44+
public static long asLong(JsonObject obj, String key, long defaultValue) {
45+
if (obj == null)
46+
return defaultValue;
47+
if (key == null)
48+
throw new IllegalArgumentException("key is null");
49+
50+
JsonElement val = obj.get(key);
51+
52+
return val != null
53+
? val.getAsLong()
54+
: defaultValue;
55+
}
56+
}

0 commit comments

Comments
 (0)