developer2015
developer2015

Reputation: 423

Map JSON default tag to java variable

I am consuming a rest service where the incoming JSon Response is something like this

 "thumbnailUrls": {
      "small": "skinresources/unpackaged/images/default_event.jpg",
      "medium": "skinresources/unpackaged/images/default_event.jpg",
      "large": "skinresources/unpackaged/images/default_event.jpg",
      "default": "skinresources/unpackaged/images/default_event.jpg"
    },

I have created a Java Class to map the Values Listed below is the Java Code Below

public class ThumbNailUrlDTO {

    private String small;

    private String medium;


    private String large;

    private String default;
}

The issue that I am having is I can't use the default name here as it is java keyword how do I deal with this problem

Upvotes: 3

Views: 772

Answers (3)

Roza
Roza

Reputation: 11

the correct answer is by adding @SerializedName("default") as follows:

public class ThumbNailUrlDTO {

private String small;

private String medium;


private String large;

@JsonProperty("default")
@SerializedName("default")
private String defaultVal;
}

Upvotes: 0

Rohit Gupta
Rohit Gupta

Reputation: 453

yes "default", invalid VariableDeclaratorId, you can not use default as variable name in java , its a pre-define keyword in java.

change variable name & map like this for json field name:- Use @JsonProperty :

public class ThumbNailUrlDTO {
    @JsonProperty("small")
    private String small;

    @JsonProperty("medium")
    private String medium;

    @JsonProperty("large")
    private String large;

    @JsonProperty("default")
    private String defaultStr;
}

This will solve the issue.

Upvotes: 5

Felix
Felix

Reputation: 48

you can use annotation to custom JSON name used for a property like this:

public class ThumbNailUrlDTO {

    private String small;

    private String medium;


    private String large;

    @JsonProperty("default")
    private String defaultVal;
}

In this way, you can avoid using java keyword "default".

Upvotes: 2

Related Questions