Closed GoogleCodeExporter closed 9 years ago
Sample code:
public Object fromJson(String json) {
JsonElement element = new JsonParser().parse(json);
return fromJson(element);
}
private Object fromJson(JsonElement element) {
if (element.isJsonNull()) {
return null;
} else if (element.isJsonPrimitive()) {
JsonPrimitive primitive = element.getAsJsonPrimitive();
if (primitive.isBoolean()) {
return primitive.getAsBoolean();
} else if (primitive.isNumber()) {
return primitive.getAsNumber();
} else if (primitive.isString()) {
return primitive.getAsString();
}
throw new AssertionError("Invalid JsonPrimitive.");
} else if (element.isJsonArray()) {
List<Object> list = new ArrayList<Object>();
for (JsonElement e : element.getAsJsonArray()) {
list.add(fromJson(e));
}
return list;
} else if (element.isJsonObject()) {
Map<String, Object> map = new HashMap<String, Object>();
for (Map.Entry<String, JsonElement> entry : element.getAsJsonObject().entrySet()) {
map.put(entry.getKey(), fromJson(entry.getValue()));
}
return map;
}
throw new AssertionError("Invalid JsonElement.");
}
Original comment by danith...@gmail.com
on 10 Sep 2012 at 4:18
You already get this with Gson.fromJson(String, Object.class)
Original comment by limpbizkit
on 4 Feb 2013 at 4:08
Original issue reported on code.google.com by
danith...@gmail.com
on 10 Sep 2012 at 3:53