Reputation: 724
I have a simple JSON string of the form {"item":"CDigital_cam_80X","manufacturer":"Canon","model":"95 IS","announced-date":"2009-02-17T19:00:00.000-05:00"}
I have created a Java Bean and written code to deserialize the string using Gson to get an object but for some reason the announced_date field returns a null every time.
Here is the code snippet for the deserialization
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create();
currentProduct = gson.fromJson(currentLine, Product.class);
Here is the product class.
import java.util.Date;
public class Product {
private String product_name;
private String manufacturer;
private String model;
private Date announced_date;
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getFamily() {
return family;
}
public void setFamily(String family) {
this.family = family;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public Date getAnnounced_date() {
return announced_date;
}
public void setAnnounced_date(Date announced_date) {
this.announced_date = announced_date;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("{ \n");
sb.append(" product_name: "); sb.append(this.getProduct_name()); sb.append("\n");
sb.append(" manufacturer "); sb.append(this.getManufacturer()); sb.append("\n");
sb.append(" family: "); sb.append(this.getFamily()); sb.append("\n");
sb.append(" model: "); sb.append(this.getModel()); sb.append("\n");
sb.append(" announced_date: "); sb.append(this.getAnnounced_date()); sb.append("\n");
sb.append("}");
return sb.toString();
}
}
Here is the result I get when I run the code and print out the preperties of the deserialized object
{
item:CDigital_cam_80X
manufacturer Canon
model:95 IS
announced-date:null
}
What is it that I am doing wrong?
Upvotes: 2
Views: 3579
Reputation: 32026
You have two issues --
In your JSON, the field is named "announced-date" but in your POJO it is "announced_date". Notice there is an underscore instead of a dash. GSON views these as two different fields. To fix that, use the @SerializeName
annotation.
@SerializedName("announced-date")
private Date announced_date;
Second, your data format is off for the time zone specifier. Z
should be an X
. Z
does not have a colon (:) in the specification. X
does. See SimpleDateFormat
.
Upvotes: 2