learner
learner

Reputation: 1321

Setting optional fields in gson annotiation request object

I have two fields in my class card and qrCode:

public class User{
    @SerializedName("card")
    private String card;

    @SerializedName("qrCode")
    private boolean qrCode
    ...
}

I make a request with this object serialized. However, in my backend these fields don't exist until deployment. The old values were objects, not String or boolean.

Because of that, I'm receiving this error in my response:

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

Is there a way to make these fields optional in my request?

My response is this JSON:

{"success":true,"msg":"founded","data":{..."card":{"success":false,"msg":"Not found","data":null}}}

Upvotes: 1

Views: 2203

Answers (2)

Michał Ziober
Michał Ziober

Reputation: 38665

You need to implement custom deserializer which converts JSON object to String:

class ObjectOrStringJsonDeserializer implements JsonDeserializer<String> {

    @Override
    public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
        if (json.isJsonPrimitive()) {
            return json.getAsJsonPrimitive().getAsString();
        }
        if (json.isJsonObject()) {
            return json.getAsJsonObject().toString();
        }
        return null;
    }
}

You can use it as below:

@SerializedName("card")
@JsonAdapter(ObjectOrStringJsonDeserializer.class)
private String card;

And example usage:

Gson gson = new GsonBuilder().create();
String json = "{\"card\":{\"success\":false,\"msg\":\"Not found\",\"data\":null}}";
System.out.println(gson.fromJson(json, User.class));

Prints:

User{card='{"success":false,"msg":"Not found","data":null}', qrCode=false}

The same you can do for boolean qrCode. You need to write custom deserialiser which converts JSON object to boolean and register it using @JsonAdapter annotation.

Upvotes: 1

Mehul Kabaria
Mehul Kabaria

Reputation: 6622

This is not issue with parameters. This is issue with your response you get.

It may be issue with you are getting JSONObject as in your response, but you cast that parameters as a string.

Upvotes: 0

Related Questions