Chris Simmons
Chris Simmons

Reputation: 259

Gson HTTP response object

I am using Gson library for first time. I am making an HTTP request and pulling response (JSON response) and need to pull a specific result.

StringBuilder response;
try (BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream()))) {
    String line;
    response = new StringBuilder();
    while((line = in.readLine()) != null) {
        response.append(line);
    }
}

Gson gson = new GsonBuilder()
                .setPrettyPrinting()
                .create();
System.out.println(gson.toJson(response));

The response looks like this below, and I need to pull only cardBackId:

[{\"cardBackId\":\"0\",\"name\":\"Classic\",\"description\":\"The only card back you\u0027ll ever need.\",\"source\":\"startup\",\"sourceDescription\":\"Default\",\"enabled\":true,\"img\":\"http://wow.zamimg.com/images/hearthstone/backs/original/Card_Back_Default.png\",\"imgAnimated\":\"http://wow.zamimg.com/images/hearthstone/backs/animated/Card_Back_Default.gif\",\"sortCategory\":\"1\",\"sortOrder\":\"1\",\"locale\":\"enUS\"

Upvotes: 0

Views: 3747

Answers (1)

Jason
Jason

Reputation: 11832

You could use JSONPath (which is a Java library for selecting parts of a JSON object) to extract just the part you need from the string.

Alternatively, you could write a class that only contains the field you want:

public class CardBackIdResponse {
    public int cardBackId;
}

And then use Gson to unmarshall the JSON into your object:

CardBackIdResponse[] cardBackIdResponses = gson.fromJson(response.toString(), CardBackIdResponse[].class);
System.out.println("cardBackId = " + cardBackIdResponses[0].cardBackId);

When unmarshalling an object from JSON, if Gson cannot find a field in the object to populate with a value from the JSON, it will just discard the value. That's the principle we could use here.

Edit: Altered answer above to handle JSON array as per this SO question.

Upvotes: 1

Related Questions