0

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?

aselims
  • 1,843
  • 1
  • 17
  • 19

1 Answers1

1

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();

Community
  • 1
  • 1
Edson Menegatti
  • 4,006
  • 2
  • 25
  • 40
  • Thx for help. I have checked these before but "yourJsonString" is coming from another call of a parent pojo... and I do not want to deserialize it. I just need it as a string. – aselims Aug 28 '15 at 08:28
  • 1
    I see, one work around is to save `@SerializedName("parameters")` as a `JsonElement`. This means it will be stored without any parsing. Afterwards you can just convert it to `String` doing `yourJsonElement.toString()` – Edson Menegatti Aug 28 '15 at 12:31
  • your comment is useful so update your answer to accept :) – aselims Aug 28 '15 at 14:11
  • It's not recommended to use `JsonDeserializer` anymore, it's been deprecated in favor of `TypeAdapter`. – durron597 Aug 28 '15 at 14:18
  • @durron597 good catch, will update the answer to reflect that – Edson Menegatti Aug 28 '15 at 14:27