I am consuming an API whose structure is as below.
{
"icao": "VIDP",
"iata": "DEL",
"name": "Indira Gandhi International Airport",
"location": "New Delhi",
"country": "India",
"country_code": "IN",
"longitude": "77.103088",
"latitude": "28.566500",
"link": "/world-airports/VIDP-DEL/",
"status": 200
}
My POJO is as below.
package com.myapp.flightreservation.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class AirportInfo {
@JsonProperty("countryCode")
private String country_code;
}
When I run my application I get the below.
{
"countryCode": null
}
If I change my POJO to below, I get the output.
package com.myapp.flightreservation.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class AirportInfo {
@JsonProperty("country_code")
private String country_code;
}
OUTPUT:
{
"country_code": "IN"
}
I want to follow the camel case in my API response. As per my knowledge, if I use @JsonProperty("countryCode"), country_code should be mapped to countryCode.
CodePudding user response:
Yes Correct. You can achieve that by using @JsonProperty("countryCode")
CodePudding user response:
If you want to consume JSON with a field called country_code (AirportInfoIn) and emit JSON with the same element called countryCode (AirportInfoOut) then you need to define 2 different POJOs. Otherwise you will trip up on the way in or out - as you have seen.
You can save some coding by using inheritance as follows:
@Data
public class AirportInfo implements Serializable {
private String icao;
private String iata;
private String name;
private String location;
private String country;
private String longitude;
private String latitude;
private String link;
private Integer status;
}
@Data
public class AirportInfoIn extends AirportInfo {
private String country_code;
}
@Data
public class AirportInfoOut extends AirportInfo {
// to make an AirportInfoOut from an AirportInfoIn
public AirportInfoOut(AirportInfoIn airportInfoIn) {
this.countryCode = airportInfoIn.getCountry_code();
this.icao = airportInfoIn.getIcao();
// etc
}
private String countryCode;
}
Note: the @JsonProperty is redundant if the Java fieldname matches the JSON