oe a
oe a

Reputation: 2280

How to read Json with Gson

HOw would I go about parsing JSON using the google GSON library? An example of my returned JSON is:

[
    {
        "title": "Down",
        "album": "Down",
        "length": 212.61,
        "artist": "Jay Sean"
    },
    {
        "title": "Come to Me (Peace)",
        "album": "Growing Pains",
        "length": 301.844,
        "artist": "Mary J Blige"
    }
]

This is an array of json objects, is that right? How would I go about extracting this with Gson? This is what im trying but am getting null pointer exceptions:

        JsonElement jelement = new JsonParser().parse(jsonInfo);
        JsonObject  jobject = jelement.getAsJsonObject();
        jobject = jobject.getAsJsonObject("");
        JsonArray jarray = jobject.getAsJsonArray("");
        jobject = jarray.get(0).getAsJsonObject();
        String result = jobject.get("title").toString();

Upvotes: 2

Views: 313

Answers (2)

Loki
Loki

Reputation: 941

You must create a Type instance for List.

    class MyObj {
        String title;
        String album;
        double length;
        String artist;
    }

    String json = "[\n" +
            "    {\n" +
            "        \"title\": \"Down\",\n" +
            "        \"album\": \"Down\",\n" +
            "        \"length\": 212.61,\n" +
            "        \"artist\": \"Jay Sean\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"title\": \"Come to Me (Peace)\",\n" +
            "        \"album\": \"Growing Pains\",\n" +
            "        \"length\": 301.844,\n" +
            "        \"artist\": \"Mary J Blige\"\n" +
            "    }\n" +
            "]";
    Type listType = new TypeToken<List<MyObj>>() {}.getType();
    List<MyObj> list = new Gson().fromJson(json, listType);
    System.out.println(new Gson().toJson(list));

Upvotes: 4

从此醉
从此醉

Reputation: 44

Gson gson = new Gson(); gson. //a lot methods

Upvotes: 0

Related Questions