I'm using Spring Restful web service using Java 1.7
I've a json mapper class which has getter / setter methods for fName, lName, address, currentTime, etc
Now, this class has below attribute:
@JsonSerialize(include = Inclusion.NON_DEFAULT)
Because of this attribute, my rest web service does not return attributes which have default values.
What needs to be done to retain these values?
If I set the Inclusion to NON_NULL, it works but then it gives problem in heartbeat API where I need only currentTime.
I've getter/setter for currentTime in same jason mapper class & this returns all other attributes with default values if I set the inclusion to NON_NULL.
How do I handle this in RESTFul services? I just want time attribute to be returned for heartbeat API & for other APIs, I need all attributes along with default values.
I'll appreciate if any one can give suggestions!!
UPDATE: Here is my code:
Controller.java
@RequestMapping(value = "heartbeat", method = RequestMethod.GET, consumes="application/json")
public ResponseEntity<String> getHeartBeat() throws Exception {
String curr_time = myService.getCurrentTime();
return MyServiceUtil.getResponse(curr_time, HttpStatus.OK);
}
@RequestMapping(value = "info", method = RequestMethod.POST, consumes="application/json")
public ResponseEntity<String> getData(@RequestBody String body) throws Exception {
....
myInfo = myService.getMyInfo(myServiceJson);
return MyServiceUtil.getResponse(myInfo, responseHeader, HttpStatus.OK);
}
MyService.java
@Override
public String getCurrentTime() throws Exception {
String currentDateTime = null;
MyServiceJson json = new MyServiceJson();
ObjectMapper mapper = new ObjectMapper();
try {
Date currDate = new Date(System.currentTimeMillis());
currentDateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(currDate);
json.setCurrentDateTime(currentDateTime);
ObjectWriter writer = mapper.writerWithView(Views.HeartBeatAPI.class);
return writer.writeValueAsString(json);
} catch (Exception e) {
throw new Exception("Excpetion in getCurrentTime: ", HttpStatus.BAD_REQUEST);
}
}
@Override
public String getMyInfo(MyServiceJson myServiceJson) throws Exception {
MyServiceJson json = new MyServiceJson();
json.setFirstName("hhh");
json.setLastName("abc");
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(json);
}
Views.java
public class Views {
public static class HeartBeatAPI { }
}
MyServiceJson.java
@JsonSerialize(include = Inclusion.NON_NULL)
public class MyServiceJson {
private int id;
private String firstName;
private String lastName;
@JsonView(Views.HeartBeatAPI.class)
private String currentDateTime;
// Getter/Setter for the above variables here
.....
}
When I run heartbeat API, I'm still getting id value as 0 which is default value.