I'd suggest to create a custom deserializer and register it in your object mapper for this particular class (say MyDateObject
). Assuming MyDateObject
has two fields - startDate
& endDate
, you can impose deserializing startDate
before endDate
using something like this:
public class CustomDeserializer extends JsonDeserializer<MyDateObject> {
@Override
public MyDateObject deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
long startDate = 0;
long endDate = 0;
while (!jsonParser.isClosed()) {
String fieldName = jsonParser.nextFieldName();
if (fieldName == null) {
break;
}
// Check the field name and assign values
// to the corresponding fields
switch (fieldName) {
case "startDate":
startDate = jsonParser.nextLongValue(0L);
break;
case "endDate":
endDate = jsonParser.nextLongValue(0L);
break;
default:
// If you have other fields in the JSON that
// you want to ignore, you can skip them.
jsonParser.skipChildren();
break;
}
}
return generateNewMyDateObject(startDate, endDate);
}
private MyDateObject generateNewMyDateObject(long startDate, long endDate) {
MyDateObject myDate = new MyDateObject();
myDate.setStartDate(startDate);
myDate.setEndDate(endDate);
return myDate;
}
}
Of course the code can be cleaner, but I'll leave it to you as the business expert. Basically, we keep the two values from the JSON content, and only after we got both of them, we generate the MyDateObject
, with startDate
first. Such that you can implement in the setter of endDate
whatever you want, and you can assume startDate
already has a value.
Then, you can register this custom deserializer to your object mapper:
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(MyDateObject.class, new CustomDeserializer());
objectMapper.registerModule(module);
And use this object mapper for deserialization:
String jsonString = "{\"endDate\":123,\"startDate\":30}";
MyDateObject customObject = objectMapper.readValue(jsonString, MyDateObject.class);
Note: If you're using Spring Boot, it's even easier. Just define this object mapper as a Bean in your @Configuration class, and let Spring use it for deserialization automatically.