How to parse REST API json data comprising of uppercase attribute name, Date and Instant in a java spring application ?

Himanshu Pratap
2 min readAug 20, 2021

--

I was trying to access a REST API server that returns json data as shown below through a java spring application.

{
"FIRST_NAME" : "Rohan",
"LAST_NAME":"KUMAR",
"DATE_OF_BIRTH": "20-SEP-1990",
"UPLOAD_DATE": "2021-05-31T06:13:23.000Z"
}

On face value , it does not look like a very complicated problem but when i started the implementation, i found it tricky.

My first attempt was to receive the json output into an object of class defined below.

public class StudentDTO{
private String FIRST_NAME;
private String LAST_NAME;
private LocalDate DATE_OF_BIRTH;
privet Instant UPLOAD_DATE;
}
public StudentDTO getStudent(){
RestTemplate restTemplate = restTemplate();
String url= “http://localhost:9000/student/1";
StudentDTO student = restTemplate.getForObject(url, StudentDTO.class);
return student;
}

Above solution failed due to following issue.

  1. Spring does not support uppercase attribute name. So despite having the attribute name “FIRST_NAME”, it gets deserialized as “FIRST_name” as json.
  2. Java Date formatter doe not supports the syntax “20-SEP-1990”. It however supports the syntax “20-Sep-1990”.
  3. As the timezone was not explicitly mentioned, parsing of Instant data “2021–05–31T06:13:23.000Z” was taking a very long time.

Correct solution is as follows:

DTO Class

public class StudentDTO{@JsonProperty("FIRST_NAME")
private String firstName;
@JsonProperty("LAST_NAME")
private String lastName;
@JsonProperty("DATE_OF_BIRTH")
@JsonDeserialize(using = LocalDateDeserializer.class) // Use custom deserializer class
private LocalDate dateOfBirth;
@JsonProperty("UPLOAD_DATE")
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX", timezone = "UTC")
private Instant uploadDate;
}

Custom LocalDate Deserializer

public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {
@Override
public LocalDate deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) throws IOException {
String strDate= jsonparser.getText();
//Convert month name from upper case to Titel case. eg. SEP to Sep
String modDate = strDate.substring(0,4)+strDate.substring(4,6).toLowerCase()+strDate.substring(6);
return LocalDate.parse(modDate, DateTimeFormatter.ofPattern("dd-MMM-yyyy"));
}
}

Function to acces REST API

public StudentDTO getStudent(){RestTemplate restTemplate = restTemplate();
String url= “http://localhost:9000/student/1";
StudentDTO student = restTemplate.getForObject(url, StudentDTO.class);
return student;
}

--

--

Himanshu Pratap
Himanshu Pratap

Written by Himanshu Pratap

System Administrator and Full stack web developer.

No responses yet