2

There is a json, contains String value for parameter, e.g. status and this json maps by Gson on POJO, and this parameter maps on custom enum. JSON:

{"status":"on"}

POJO

public class StatusData {
    @SerializedName("status")
    @Expose
    private Status status;
}

enum:

public enum Status {
   @SerializedName("on")ON,
   @SerializedName("off")OFF;
}

And if json contains correct values ("on" or "off") - all right, but if there is unsupported value e.g. "unknown" - then it crushes with Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference. And question: is there way to change message of exception for understanding what went wrong?

2 Answers 2

1

No need to create new class of enum

Use http://www.jsonschema2pojo.org/ to generate pojo class

Try this

public class StatusData
{
    @SerializedName("status")
    @Expose
    private String status;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I wanna then work with enum, but no String, I know that I can change getters and setters and maps String and Enum there, but I just want throw exception with understandable description
0
public class StatusData {
@SerializedName("status")
@Expose
private Status status;

public String getStatus() {
    return status;
}
}

Save your response as an object of StatusData

StatusData statusData=response;
String status=statusData.getStatus();
if(status.equals("on")){
  //code when status is "on"
} else if(status.equals("off")){
  //code when status is "off"
}

or use gson

Gson gson = new Gson();
StatusData statusData = gson.fromJson("json response",
                                        StatusData.class);

1 Comment

Yes, it will help to get around the problem, but I want just set custom message for exception, maybe some Strategies of Gson can help to solve this problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.