aselims
aselims

Reputation: 1893

Custom GSON parsing

I have the following pojo:

 public class  PageRedirect implements Parcelable {

@SerializedName("method") private String method;
@SerializedName("url") private String url;
@SerializedName("parameters") private Parameters parameters;

//@SerializedName("parameters") private String params;
......}

The parameters field is changing depends on some parameter with the originating API. So sometimes it is {} "json object" and if it is empty, it is array []. I know this is a fault in the Backend. But I would like to find a quick work around... Instead of parsing the parameters, I just would like to get it as a string as the commented line and then I will process it. Any ideas?

Upvotes: 0

Views: 266

Answers (1)

Edson Menegatti
Edson Menegatti

Reputation: 4036

When creating your instance of Gson, you can set a custom class deserializer as follows:

final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Parameter.class, new ParameterTypeAdapter());
final Gson gson = gsonBuilder.create();

PageRedirect pageRedirect = gson.fromJson(yourJsonString, PageRedirect.class);

Then you can create your ParameterTypeAdapter as follows:

public class ParameterTypeAdapter extends TypeAdapter<Parameter> {

@Override
public void write(JsonWriter out, Calendar value) throws IOException {

}

@Override
public Calendar read(JsonReader in) throws IOException {
    // do your parsing here
}

You can find more info on it here and here.

EDIT:

If you just want to defer parsing to another moment, you can store your "parameters" field as a JsonElement:

@SerializedName("parameters") private JsonElement parameters;

Afterwards, just convert it to String by using parameters.toString();

Upvotes: 1

Related Questions