mjhuang
mjhuang

Reputation: 11

Serializing two Date fields with different format

I am trying to serialize a class that has two Date fields defined:

public class DateBean {
    public Date startDate;
    public Date endDate;
    public DateBean(Date startDate, Date endDate) {
        this.startDate = startDate;
        this.endDate = endDate;
    }
}
Gson gson =  new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
String json=gson.toJson(new DateBean(new Date(),new Date()));
System.out.println(json);

default result is

{"startDate":2020-06-10,"endDate":2020-06-10}

expect results is

{"startDate":2020-06-10,"endDate":2020-06-10 12:00:00}

Upvotes: 1

Views: 92

Answers (1)

Marc Stroebel
Marc Stroebel

Reputation: 2357

you could create a custom serializer

public class DateBeanGsonSerializer implements JsonSerializer<DateBean> {
    private SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    private SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

    @Override
    public JsonElement serialize(DateBean bean, Type type,
        JsonSerializationContext jsonSerializationContext) {

        JsonObject jsonObj = new JsonObject();

        jsonObj.addProperty("startDate", 
          bean.startDate != null ? 
          sdf.format(bean.startDate) : null);

        jsonObj.addProperty("endDate", 
          bean.endDate != null ? 
          sdf2.format(bean.endDate) : null);



        return jsonObj;
    }
}

and use it....

Gson gson = new GsonBuilder()
  .registerTypeAdapter(DateBean.class, new DateBeanGsonSerializer())
  .create();

Upvotes: 1

Related Questions