jjj
jjj

Reputation: 2672

JSON parsing issue (get attributes)

I have parsed JSON using GSON, and out of object got the element I needed:

JsonObject obj=str.getAsJsonObject();
JsonElement search=obj.get("value");

Now, the GSON JsonElement 'search' contains following JSON:

[{"title":"John Lennon","snippet":"English musician, singer"}]

Formatted:

[
    {
        "title": "John Lennon",
        "snippet": "English musician, singer",
    }
]

I need to extract out following two values title and snippet. How?

Upvotes: 0

Views: 62

Answers (2)

T J
T J

Reputation: 43166

From the looks of it, you can use getAsJsonArray()

JsonObject obj= str.getAsJsonObject();
JsonElement search= obj.get("value").getAsJsonArray().get(0)

search.get("title") //John Lennon

and

search.get("snippet") // English musician, singer

Upvotes: 2

heikkim
heikkim

Reputation: 2975

Use JsonElement#getAsJsonArray():

JsonElement firstEntry = search.getAsJsonArray().get(0);
firstEntry.get("title") // => John Lennon
firstEntry.get("snippet") // => English musician, singer

If it is not certain that the element actually is an array, then use JsonElement#isJsonArray() as a pre-condition:

if(search.isJsonArray()) {
    JsonElement firstEntry = search.getAsJsonArray().get(0);
    firstEntry.get("title") // => John Lennon
    firstEntry.get("snippet") // => English musician, singer
}

Upvotes: 1

Related Questions