Eliminate duplicate Json elements and retrieve element names starting with capital letters spring boot/java
public class ValidateResponse { @JsonProperty("ResponseDesc") public String responseCode; @JsonProperty("ResponseDesc") public String responseDesc; //getters and setters //constructors using fields //empty constructor}
This must fix your problem, however I do not know the reason as it requires deep Jackson investigation.
EDIT
I found out the reason.The field got duplicated because in you case you had:
- 2 public fields named in upper case -> they are to be processed by jackson
- 2 getters
getResponseCode
andgetResponseDesc
-> they are to be resolved as accessors for propertiesresponseCode
andresponseDesc
accordingly.
Summing this up - you have 4 properties resolved by Jackson. Simply making your fields private will resolve your issue, however I still advise using JsonProperty
approach.
Jackson
deserializes all the public fields that it comes across. However if you want Jackson
to return the response in your expected element names (in your case elements starting with capital letters), make the fields private
and annotate them with the @JsonProperty(expected_name_here)
. Your class file will typically looks as shown below
public class ValidateResponse { @JsonProperty("ResponseDesc") private String responseCode; @JsonProperty("ResponseDesc") private String responseDesc; //getters and setters //constructors using fields //empty constructor}
Note: The getters and setters for these fields should be
public
, otherwiseJackson
won't see anything to deserialize in the class.
I added a com.google.code.gson
dependency in the projects pom.xml
file to configure Spring Boot to use Gson (instead of the default jackson).
The Json object returned from the hooks/validate
endpoint must have its property names starting with a capital letter. Using a java class to generate the response object was resulting to camelCased
property names so I resolved to create the JSON response object manually. Here's the code for creating the custom JSON object:
public ResponseEntity<String> responseObj(@RequestHeader Map<String, String> headersObj) { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.APPLICATION_JSON); JsonObject response = new JsonObject(); response.addProperty("ResponseCode", "00000000"); response.addProperty("ResponseDesc" , "Success"); logger.info("Endpoint = hooks/validate | Request Headers = {}", headersObj); return ResponseEntity.ok().headers(responseHeaders).body(response.toString());}
Note The JSON object is returned as a String
so the response from the endpoint must have an additional header to define MediaType
to inform the calling system that the response is in JSON format:
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
then add the header to the response:
return ResponseEntity.ok().headers(responseHeaders).body(response.toString());