我已经使用GSON序列化和反序列化模型类JSON字符串,但问题是GSON发生日期variabless为timestamp serializer.My类同时包含日期和时间戳变量,但两者都是由相同的时间戳serializer.I连载已经写了两时间戳和在我GsonBuilder.Below日期串是我的课
StaffDetails.java:
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Locale;
@Entity
@Table(name = "staff_details")
public class StaffDetails implements Serializable {
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@Column(name="address")
private String address;
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
@Column(name = "dob")
private Date dob;
@Column(name="created_by")
private Long createdBy;
@Column(name="created_on")
private Timestamp createdOn;
public StaffDetails() {
}
public StaffDetails(Long id, String address, String name, Integer age, Date dob, Long createdBy, Timestamp createdOn) {
this.id = id;
this.address = address;
this.name = name;
this.age = age;
this.dob = dob;
this.createdBy = createdBy;
this.createdOn = createdOn;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Long getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
}
下面是我GSON串行
String jsonAccts = null;
SimpleDateFormat dtf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
SimpleDateFormat dtfDate=new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
try{
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
@Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
String jsDate = dtfDate.format(src);
return new JsonPrimitive(jsDate);
}
});
builder.registerTypeAdapter(Timestamp.class, new JsonSerializer<Timestamp>() {
@Override
public JsonElement serialize(Timestamp src, Type typeOfSrc, JsonSerializationContext context) {
String jsDate = dtf.format(src);
return new JsonPrimitive(jsDate);
}
});
Gson gson = builder.create();
Type listType = new TypeToken<List<StaffDetails>>() {}.getType();
List<StaffDetails> staffDetailsList = new ArrayList<StaffDetails>();
staffDetailsList = loopDao.getStaffLeaveList(customUser.getId());
jsonAccts = gson.toJson(staffDetailsList, listType);
}catch(Exception e){
e.printStackTrace();
}
问题是这两个出生日期和createdBy要TIMESTAMP串行器。 我要的是出生日期应该去日期串行和createdBy为TIMESTAMP serializer.Please帮助我。