Question

What should I do to convert json response to object(pojo) using GSON lib? I have response from webservice:

{"responce":{"Result":"error","Message":"description"}}

and create POJO

public class ErrorResponse {

    private String result;
    private String message;
}

but

ErrorResponse errorResponse = (ErrorResponse) gson.fromJson(new String(responseBody), ErrorResponse.class);

gets an error

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 14

UPD

OK, i created

public class Wrapper {
    @SerializedName("Responce")
    private ErrorResponse response;
// get set
}


public class ErrorResponse {
    @SerializedName("Result")
    private String result;
    @SerializedName("Message")
    private String message;
// get set


 Wrapper wrapper = (Wrapper) gson.fromJson(new String(responseBody), Wrapper.class);
                        ErrorResponse errorResponse = wrapper.getResponse();

and finally I get NPE errorResponse

Was it helpful?

Solution

Your JSON is actually a JSON object containing a JSON object named response. That JSON object has the format of your Pojo.

So one option is to create that hierarchy in Java

public class Wrapper {
    private ErrorResponse response;
    // getters & setters
}

And deserialize that

Wrapper wrapper = (Wrapper) gson.fromJson(new String(responseBody), Wrapper.class);
ErrorResponse errorResponse = wrapper.getResponse();

An alternative is to parse the JSON into a JsonElement which you use to get the JSON object named response and convert that one. Use the following types from the Gson library:

import com.google.gson.JsonParser;
import com.google.gson.GsonBuilder;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
//...

Gson gson = new GsonBuilder().create();
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(json);
ErrorResponse response = gson.fromJson(jsonElement.getAsJsonObject().get("response"), ErrorResponse.class);

Note that your class' field names must match the JSON or vice versa. result vs Result. Or you can use @SerializedName to make it match

@SerializedName("Response")
private String response;

OTHER TIPS

You can use jsonschema2pojo online POJO generator to generate a POJO class from a JSON document or JSON schema with the help of GSON library. In the 'Annotation style' section, choose GSON. Once the zip file is created, extract it and add all the classes to your classpath. Note: you will need to add GSON jars to your project.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top