Search code examples
javaandroidjsongsonpojo

Why does this json parse with null attributes?


I have the following code, JSON and POJO, however even though the JSON attributes have values, the resulting dataToUse object has null for name and date. Is there a special way to handle '@' in the json? I have another exactly similar piece of code which parses properly, but there is no '@'.

DataToUse dataToUse = new Gson().fromJson(json.toString(), DataToUse.class);

JSON:

{“@name”: “A Name”,“@date”: "2017-12-11T18:00:00-05:00"}

POJO:

public class DataToUse {
    private String name;
    private Date date;

    public String getName() { return this.name; }
    public void setName(String name) { this.name = name; }

    public Date getDate() { return this.date; }
    public void setDate(Date date) { this.date = date; }
}

Solution

  • Try below, by adding @SerializedName annotation

        public class DataToUse {
            @SerializedName("@name")
            private String name;
            @SerializedName("@date")
            private Date date;
    
            public String getName() { return this.name; }
            public void setName(String name) { this.name = name; }
    
            public Date getDate() { return this.date; }
            public void setDate(Date date) { this.date = date; }
        }