asolfre / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

Implement "Object fromJson(String json)" #470

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
I'd like to propose to add a non-generic method to Gson: Object fromJson(String 
json). The return value is either a primitive, a List, or a Map. The benefit is 
that you don't need to provide the 2nd parameter (either Class or Type) when 
you don't know the type of the json string. This might not be that useful for 
you Java application, but it would be super helpful for JSR-223 (scripting 
language) such as Jython. 

Let me know if you guys like the idea or not. I can contribution a patch if 
needed.

Original issue reported on code.google.com by danith...@gmail.com on 10 Sep 2012 at 3:53

GoogleCodeExporter commented 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

GoogleCodeExporter commented 9 years ago
You already get this with Gson.fromJson(String, Object.class)

Original comment by limpbizkit on 4 Feb 2013 at 4:08