ObjectMapper SetDateFormat() is not working - java

I have used ObjectMapper to map a object to Json String.
I have date Fields in the object to format the date i have used the below code but it is not formatting as expected.
My Json String:
{"leaveRequestId":51,"reason":"xdvfsgf","leaveFromDate":"2016-07-13","leaveToDate":"2016-07-15","leaveTypeId":9,"statusId":1,"instanceId":"7527","createdBy":"pramod","createdOn":"2016-07-07","modifiedBy":null,"modifiedOn":null}
I am using the below code:
#RequestMapping(value="/getLeaveRequest", method = RequestMethod.GET)
#ResponseBody
public String getLeaveRequest( int leaveRequestId) throws Exception {
DAOFactory obj_daofactory=new DAOFactory();
ObjectMapper mapper = new ObjectMapper();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MMM-dd");
mapper.setDateFormat(df);
LeaveRequest leaveRequest = obj_daofactory.getLeaveRequestDao().findByLeaveRequestId(leaveRequestId);
if(leaveRequest.getLeaveRequestId() == 0){
return "No data found";
} else {
System.out.println(leaveRequest.getLeaveFromDate().toString());
String jsonInString = mapper.writeValueAsString(leaveRequest);
System.out.println(jsonInString);
return jsonInString;
}
}
MY Expected OutPut:
{"leaveRequestId":45,"reason":"test","leaveFromDate":"2016-Jul-07","leaveToDate":"2016-Jul-08","leaveTypeId":9,"statusId":1,"instanceId":"test1","createdBy":"deepak.paul#muraai.com","createdOn":"2016-Jul-07","modifiedBy":"pramod","modifiedOn":"2016-Jul-08"}
Date must be in the "2016-Jul-07" format
LeaveRequest.java
import java.util.Date;
public class LeaveRequest {
private int leaveRequestId;
private String reason;
private Date leaveFromDate;
private Date leaveToDate;
private int leaveTypeId;
private int statusId;
private String instanceId;
private String createdBy;
private Date createdOn;
private String modifiedBy;
private Date modifiedOn;
public LeaveRequest() {
}
public LeaveRequest(int leaveRequestId, String reason, Date leaveFromDate, Date leaveToDate,int leaveTypeId,int statusId, String instanceId,
String createdBy, Date createdOn, String modifiedBy, Date modifiedOn) {
this.leaveRequestId=leaveRequestId;
this.reason=reason;
this.leaveFromDate=leaveFromDate;
this.leaveToDate=leaveToDate;
this.leaveTypeId=leaveTypeId;
this.statusId=statusId;
this.instanceId=instanceId;
this.createdBy=createdBy;
this.createdOn=createdOn;
this.modifiedBy=modifiedBy;
this.modifiedOn=modifiedOn;
}
public LeaveRequest(String reason, Date leaveFromDate, Date leaveToDate,int leaveTypeId,int statusId, String instanceId,
String createdBy, Date createdOn) {
this.reason=reason;
this.leaveFromDate=leaveFromDate;
this.leaveToDate=leaveToDate;
this.leaveToDate=leaveToDate;
this.leaveTypeId=leaveTypeId;
this.statusId=statusId;
this.instanceId=instanceId;
this.createdBy=createdBy;
this.createdOn=createdOn;
}
public int getLeaveRequestId() {
return leaveRequestId;
}
public void setLeaveRequestId(int leaveRequestId) {
this.leaveRequestId = leaveRequestId;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public Date getLeaveToDate() {
return leaveToDate;
}
public void setLeaveToDate(Date leaveToDate) {
this.leaveToDate = leaveToDate;
}
public Date getLeaveFromDate() {
return leaveFromDate;
}
public void setLeaveFromDate(Date leaveFromDate) {
this.leaveFromDate = leaveFromDate;
}
public int getStatusId() {
return statusId;
}
public void setStatusId(int statusId) {
this.statusId = statusId;
}
public int getLeaveTypeId() {
return leaveTypeId;
}
public void setLeaveTypeId(int leaveTypeId) {
this.leaveTypeId = leaveTypeId;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public Date getModifiedOn() {
return modifiedOn;
}
public void setModifiedOn(Date modifiedOn) {
this.modifiedOn = modifiedOn;
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
}

As you said you input is 2016-07-13 which is yyyy-MM-dd format. You have to read it using yyyy-MM-dd and while writing use yyyy-MMM-dd
ObjectMapper mapper = new ObjectMapper();
try {
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
LeaveRequest lrq = mapper.readValue("{\"leaveRequestId\":51,\"reason\":\"xdvfsgf\",\"leaveFromDate\":\"2016-07-13\",\"leaveToDate\":\"2016-07-15\",\"leaveTypeId\":9,\"statusId\":1,\"instanceId\":\"7527\",\"createdBy\":\"pramod\",\"createdOn\":\"2016-07-07\",\"modifiedBy\":null,\"modifiedOn\":null}", LeaveRequest.class);
System.out.println(mapper.setDateFormat(new SimpleDateFormat("yyyy-MMM-dd")).writeValueAsString(lrq));
} catch (IOException ex) {
Logger.getLogger(NewClass1.class.getName()).log(Level.SEVERE, null, ex);
}

I wrote this code to convert date to "yyyy-MM-dd" which ideally should have worked but it didn't
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setTimeZone(TimeZone.getDefault());
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(dateFormat);
myObj =objectMapper.readValue(file,MyObj.class)
Output was coming as - "paymentDate": "2019-08-18T23:00:00.000+0000", which isnt what I was expecting..
Changed this to Declaring ObjectMapper as a Bean and then inject ObjectMapper as a dependency
//Make sure the class is annotated with #Configuration or appropriate
#Bean
public ObjectMapper objectMapper() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setTimeZone(TimeZone.getDefault());
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(dateFormat);
return mapper;
}
and in-service class, just inject this as a dependency
#Autowired
private ObjectMapper objectMapper;
somemethod(){
myObj =objectMapper.readValue(file,MyObj.class)
}
Output was coming as -"paymentDate": "2019-08-19" -as expected

Serialization and deserialization will have to come into picture when you manipulate/modify the contents as per your requirement through ObjectMapper. You can refer more about this here
This topic has also been discussed here.

Related

Add Temporal annoation as Date skips Gson Serialization on Rest api Request

In my java application i was using REST API that returned data in JSON format, and noticed that this particular API formatted it's dates in a peculiar way: "Nov 1, 2019" , But problem is that the actual date on the server is "2019-11-02".That means I am getiing date minimized to previous date.I have added gson serialization for both Date and Timestamp values using UTC timezone format, but what i noted is the Date values skip the serialization part on the code and only Timestamp values are using the serialization.I have used #Temporal(TemporalType.DATE) for date values that why it skips the date serialization.My server is on another country.Below is the complete json that i got after formatting.
jsonAccts [{"id":8,"userId":2,"departmentId":45,"effectiveFrom":"Jun 9, 2019","endsOn":"Nov 1, 2019","createdBy":2,"createdOn":"2019-11-02 05:34:11"}]
Below is the code that i used for gson formatting.
Gson gson;
GsonBuilder builder;
SimpleDateFormat dtf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
SimpleDateFormat dtfDate=new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String jsonAccts = null;
try{
builder = new GsonBuilder();
builder.registerTypeAdapter(Timestamp.class, new JsonSerializer<Timestamp>() {
#Override
public JsonElement serialize(Timestamp src, Type typeOfSrc, JsonSerializationContext context) {
dtf.setTimeZone(TimeZone.getTimeZone("UTC"));
String jsDate = dtf.format(src);
return new JsonPrimitive(jsDate);
}
});
builder.registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
#Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
dtf.setTimeZone(TimeZone.getTimeZone("UTC"));
String jsDate = dtf.format(src);
return new JsonPrimitive(jsDate);
}
});
gson = builder.create();
List<ClassTeacher> allActPgmMap = new ArrayList<ClassTeacher>();
allActPgmMap = springDao.getClassTeacherList(Integer.parseInt(deptId));
Type listType = new TypeToken<List<ClassTeacher>>() {}.getType();
jsonAccts = gson.toJson(allActPgmMap, listType);
}catch(Exception e){
e.printStackTrace();
}
return jsonAccts;
Here the builder.registerTypeAdapter(Date.class, new JsonSerializer<Date>() {} is been not used for effectiveFrom and endsOn on api request.
Below is the ClassTeacher class.
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
#Entity
#Table(name = "class_teacher")
public class ClassTeacher implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private long id;
#Column(name = "user_id")
private long userId;
#Column(name = "department_id")
private long departmentId;
#Column(name = "effective_from")
#Temporal(TemporalType.DATE)
private Date effectiveFrom;
#Column(name = "ends_on")
#Temporal(TemporalType.DATE)
private Date endsOn;
#Column(name="created_by")
private long createdBy;
#Column(name="created_on")
private Timestamp createdOn;
public ClassTeacher() {
}
public ClassTeacher(long id, long departmentId, long userId, Date effectiveFrom, Date endsOn, long createdBy, Timestamp createdOn) {
this.id = id;
this.departmentId = departmentId;
this.userId = userId;
this.effectiveFrom = effectiveFrom;
this.endsOn = endsOn;
this.createdBy = createdBy;
this.createdOn = createdOn;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public long getDepartmentId() {
return departmentId;
}
public void setDepartmentId(long departmentId) {
this.departmentId = departmentId;
}
public Date getEffectiveFrom() {
return effectiveFrom;
}
public void setEffectiveFrom(Date effectiveFrom) {
this.effectiveFrom = effectiveFrom;
}
public Date getEndsOn() {
return endsOn;
}
public void setEndsOn(Date endsOn) {
this.endsOn = endsOn;
}
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;
}
}
Here the createdOn is using the builder.registerTypeAdapter(Timestamp.class, new JsonSerializer<Timestamp>() {},but effectiveFrom and endsOn are not using the serializer.I have used 'com.google.code.gson:gson:2.8.1' here for gson.

How to convert Date to string in realm

I am developing app now I want to convert Date to String in realm but I have tried but I can't achieve what I want
below SaveMessage model class
#RealmClass
public class SaveMessage extends RealmObject {
private int mId;
private String mUsername;
private String mContent;
private Date mCreatedAt;
private boolean mRightMessage;
private String mPictureString;
private String mType;
public SaveMessage(int id, String username, String content, Date createdAt, boolean isRightMessage) {
mId = id;
mUsername = username;
mContent = content;
mCreatedAt = createdAt;
mRightMessage = isRightMessage;
}
public SaveMessage() {
}
public int getId() {
return mId;
}
public String getUsername() {
return mUsername;
}
public String getContent() {
return mContent;
}
public Date getDate() {
return mCreatedAt;
}
public void setDate(Date createdAt) {
mCreatedAt = createdAt;
}
below my Date conversion
SimpleDateFormat input = new
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); SimpleDateFormat
output = new SimpleDateFormat("dd/MM/yyyy");
Date d = new Date();
try {
d = input.parse(output);
} catch (ParseException e) {
e.printStackTrace();
}
public boolean ismRightMessage() {
return mRightMessage;
}
public int getmId() {
return mId;
}
public void setmId(int mId) {
this.mId = mId;
}
public String getmUsername() {
return mUsername;
}
public void setmUsername(String mUsername) {
this.mUsername = mUsername;
}
public String getmContent() {
return mContent;
}
public void setmContent(String mContent) {
this.mContent = mContent;
}
public boolean ismRightMessage(String isRightMessage) {
return mRightMessage;
}
public void setmRightMessage(boolean mRightMessage) {
this.mRightMessage = mRightMessage;
}
public String getPictureString() {
return mPictureString;
}
public void setPictureString(String pictureString) {
mPictureString = pictureString;
}
public String getType() {
return mType;
}
public void setType(String type) {
mType = type;
}
}

How to retrieve data from database based on date in java?

Here is what I have tried
Controller:
public void lovForFincurrency() {
LOG.info("\n\n\nINSIDE \n CLASS == LovController \n METHOD == lovForFincurrency(); ");
try {
apexManagerService = ServiceManagerFactory.getServiceManager(getServletContext());
MmsBean mmsBean = (MmsBean) getControllerObject(ApexManagedBean.MMSBEAN.getName(), MmsBean.class);
PmBean pmBean = (PmBean) getControllerObject(ApexManagedBean.PMBEAN.getName(), PmBean.class);
final FinCurrencyService finsurrencyservice = apexManagerService.getFinCurrencyService();
DateFormat dateFormat = new SimpleDateFormat("MM/DD/YYYY HH:mm:ss");
Date date = new Date();
List<Fincurrency> fincurrencies = finsurrencyservice.readcurrencies("Y", date);
List<Admlov> admlovs = new ArrayList<Admlov>();
for (Fincurrency fincurrency : fincurrencies) {
Admlov admlov = new Admlov();
admlov.setId(fincurrency.getCurrency());
admlov.setCode(fincurrency.getSymbol());
admlov.setDescr(fincurrency.getDescr());
admlovs.add(admlov);
}
if (admlovs != null) {
mmsBean.setAdmlovs(admlovs);
}
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
addMessageToFacesContext(ERROR_DELETE);
}
LOG.info("EXITING THIS METHOD \n\n\n");
}
Here is my Repository:
public interface FinCurrencyRepo extends JpaRepository<Fincurrency, String> {
List<Fincurrency> findByEffectivefromAfterAndEffectivetoBeforeAndEnabled(Date sysdate, Date sysdate1,
String enabled);
}
Here is my serviceimplementation:
#Override
public List<Fincurrency> readcurrencies(String enabled, Date sysdate) {
return fincurrencyRepo.findByEffectivefromAfterAndEffectivetoBeforeAndEnabled(sysdate, sysdate, enabled);
}
Here is my Fincurrency Entity: I want to show symbol and currency in datatable of this year and after this year but not before this year. Kindly help me in this issue.
public class Fincurrency implements Serializable {
#Id
private String currency;
//#Temporal(TemporalType.DATE)
private Date effectivefrom;
//#Temporal(TemporalType.DATE)
private Date effectiveto;
private String enabled;
private String symbol;
#Column(name="\"TYPE\"")
private String type;
public Fincurrency() {
}
public String getCurrency() {
return this.currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public BigDecimal getAfterdecimal() {
return this.afterdecimal;
}
public void setAfterdecimal(BigDecimal afterdecimal) {
this.afterdecimal = afterdecimal;
}
public Date getEffectivefrom() {
return this.effectivefrom;
}
public void setEffectivefrom(Date effectivefrom) {
this.effectivefrom = effectivefrom;
}
public Date getEffectiveto() {
return this.effectiveto;
}
public void setEffectiveto(Date effectiveto) {
this.effectiveto = effectiveto;
}
public String getEnabled() {
return this.enabled;
}
public void setEnabled(String enabled) {
this.enabled = enabled;
}
public String getSymbol() {
return this.symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
}

#JsonFormat not working in nested object

I have a very simple bean:
public class StatusBean {
private String name;
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="MM-dd-yyyy")
private Date startDate;
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="MM-dd-yyyy")
private Date endDate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
}
And I wrap it in another bean that I use to wrap objects for nice json formatting with messages and stuff:
public class ResponseBean {
private boolean success = false;
private String message;
private Object data;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
In my controller, I set the Status bean inside the response bean with a setData();
Spring serializes this out in JSON format, however the output for the date is not formatting. I am getting the standard "yyyy-MM-DD" format.
Am I doing something wrong? How do I get this to work?
I had the same issue and fixed simply adding #JsonSerialize(as = Date.class) before #JsonFormat(shape=JsonFormat.Shape.STRING, pattern="MM-dd-yyyy")
With #DateTimeFormat(pattern="dd/MM/yyyy") from
org.springframework.format.annotation.DateTimeFormat worked for me.
I have never tried it but the solution could be to add this annotation in your ResponseBean:
#JsonSerialize(as = StatusBean.class)
private Object data;
unfortunately your Object will become a StatusBean
Possibility not write object with ObjectMapper
new ObjectMapper().writeValueAsString(MyObject);
Full code example
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writeValueAsString(new Foo(new java.util.Date())));
System.out.println(objectMapper.writeValueAsString(new Foo(new java.sql.Date(System.currentTimeMillis()))));
}
static class Foo {
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy", timezone="EST")
private Date birthdate;
public Foo() {
}
public Foo(Date birthdate) {
this.birthdate = birthdate;
}
public Date getBirthdate() {
return birthdate;
}
}

Is there a way to set the order of Xstream serialization

I need to generate XML from java objects on Android. XML nodes must be in definite sequence.
Due XStream documentation order of XML nodes match object's fields define. There is no problems when I use java classes(String, Date...) as fields. But there is problem when I need serialize my objects as fields.
Here is my code:
final XStream x = new XStream();
x.autodetectAnnotations(true);
SecondEntity secondEntity = new SecondEntity();
secondEntity.setSecondaryDate(new Date());
secondEntity.setSecondaryString("Secondary String");
InnerEntity innerEntity = new InnerEntity();
innerEntity.setInnerDate(new Date());
innerEntity.setInnerString("Inner String");
SomeEntity someEntity = new SomeEntity();
someEntity.setInnerEntity(innerEntity);
someEntity.setSecondEntity(secondEntity);
someEntity.setSomeDate(new Date());
someEntity.setSomeString("Some string");
x.toXML(someEntity)
SomeEntity:
#XStreamAlias("SomeEntity")
public class SomeEntity {
#XStreamAlias("innerEntity")
private InnerEntity innerEntity;
#XStreamAlias("secondEntity")
private SecondEntity secondEntity;
#XStreamAlias("someString")
private String someString;
#XStreamAlias("someDate")
private Date someDate;
public InnerEntity getInnerEntity() {
return innerEntity;
}
public void setInnerEntity(InnerEntity innerEntity) {
this.innerEntity = innerEntity;
}
public SecondEntity getSecondEntity() {
return secondEntity;
}
public void setSecondEntity(SecondEntity secondEntity) {
this.secondEntity = secondEntity;
}
public String getSomeString() {
return someString;
}
public void setSomeString(String someString) {
this.someString = someString;
}
public Date getSomeDate() {
return someDate;
}
public void setSomeDate(Date someDate) {
this.someDate = someDate;
}
}
InnerEntity:
#XStreamAlias("InnerEntity")
public class InnerEntity {
#XStreamAlias("innerString")
private String innerString;
#XStreamAlias("innerDate")
private Date innerDate;
public String getInnerString() {
return innerString;
}
public void setInnerString(String innerString) {
this.innerString = innerString;
}
public Date getInnerDate() {
return innerDate;
}
public void setInnerDate(Date innerDate) {
this.innerDate = innerDate;
}
}
SecondEntity:
#XStreamAlias("SecondEntity")
public class SecondEntity {
#XStreamAlias("secondaryString")
private String secondaryString;
#XStreamAlias("secondaryDate")
private Date secondaryDate;
public String getSecondaryString() {
return secondaryString;
}
public void setSecondaryString(String secondaryString) {
this.secondaryString = secondaryString;
}
public Date getSecondaryDate() {
return secondaryDate;
}
public void setSecondaryDate(Date secondaryDate) {
this.secondaryDate = secondaryDate;
}
}
I get
<SomeEntity>
<innerEntity>
<innerDate>2013-02-28 18:04:24.184 UTC</innerDate>
<innerString>Inner String</innerString>
</innerEntity>
<secondEntity>
<secondaryDate>2013-02-28 18:04:24.183 UTC</secondaryDate>
<secondaryString>Secondary String</secondaryString>
</secondEntity>
<someDate>2013-02-28 18:04:24.184 UTC</someDate>
<someString>Some string</someString>
</SomeEntity>
When I need:
<SomeEntity>
<innerEntity>
<innerString>Inner String</innerString>
<innerDate>2013-02-28 18:04:24.184 UTC</innerDate>
</innerEntity>
<secondEntity>
<secondaryString>Secondary String</secondaryString>
<secondaryDate>2013-02-28 18:04:24.183 UTC</secondaryDate>
</secondEntity>
<someDate>2013-02-28 18:04:24.184 UTC</someDate>
<someString>Some string</someString>
</SomeEntity>
Please Implement this interface FieldKeySorter for InnerEntity and SecondEntity.

Categories

Resources