[英]How to bind JSON Object to POJO
I am consuming an API whose structure is as below.我正在消费一个 API,其结构如下。
{
"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.我的 POJO 如下。
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.如果我将我的 POJO 更改为以下内容,我将得到 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: OUTPUT:
{
"country_code": "IN"
}
I want to follow the camel case in my API response.我想在我的 API 回复中遵循驼峰案例。 As per my knowledge, if I use @JsonProperty("countryCode"), country_code should be mapped to countryCode.据我所知,如果我使用@JsonProperty("countryCode"),country_code 应该映射到countryCode。
Yes Correct.是,对的。 You can achieve that by using @JsonProperty("countryCode")您可以通过使用 @JsonProperty("countryCode") 来实现
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.如果您想使用名为 country_code (AirportInfoIn) 的字段使用 JSON 并使用名为 countryCode (AirportInfoOut) 的相同元素发出 JSON,那么您需要定义 2 个不同的 POJO。 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:您可以使用 inheritance 节省一些编码,如下所示:
@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注意:如果 Java 字段名与 JSON 匹配,@JsonProperty 是多余的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.