I have an interface that first retrieves data from a third-party API, and then returns JSON to the front end for display.
Example of the response from the third-party API:
{
"ShipperCode": "SF",
"SendProvince": "",
"SendCity": "",
"SendArea": "",
"SendAddress": "",
"ReceiveProvince": "",
"ReceiveCity": "",
"ReceiveArea": "",
"ReceiveAddress": "",
"DeliveryTime": "",
"DeliveryDate": "",
"Hour": "",
"PredictPath": ""
}
Now I have defined a PredictTimeDO
object to receive the results from the third-party API:
public class PredictTimeDO {
@JsonProperty("ShipperCode")
private String shipperCode;
@JsonProperty("SendProvince")
private String sendProvince;
@JsonProperty("SendCity")
private String sendCity;
@JsonProperty("SendArea")
private String sendArea;
@JsonProperty("SendAddress")
private String sendAddress;
@JsonProperty("ReceiveProvince")
private String receiveProvince;
@JsonProperty("ReceiveCity")
private String receiveCity;
@JsonProperty("ReceiveArea")
private String receiveArea;
@JsonProperty("ReceiveAddress")
private String receiveAddress;
@JsonProperty("DeliveryTime")
private String deliveryTime;
@JsonProperty("DeliveryDate")
private String deliveryDate;
@JsonProperty("Hour")
private String hour;
@JsonProperty("PredictPath")
private String predictPath;
}
So how can I convert this JSON to return with lowercase field names to the front end? Like this:
{
"shipperCode": "",
"sendProvince": "",
"sendCity": "",
"sendArea": "",
"sendAddress": "",
"receiveProvince": "",
"receiveCity": "",
"receiveArea": "",
"receiveAddress": "",
"deliveryTime": "",
"deliveryDate": "",
"hour": "",
"predictPath": ""
}
I know one way is to define a PredictTimeDTO
object copying the values from PredictTimeDO
object:
public class PredictTimeDTO {
private String shipperCode;
private String sendProvince;
private String sendCity;
private String sendArea;
private String sendAddress;
private String receiveProvince;
private String receiveCity;
private String receiveArea;
private String receiveAddress;
private String deliveryTime;
private String deliveryDate;
private String hour;
private String predictPath;
}
Any other graceful way to resolve this?
You could use @JsonAlias for your case. It allows reading (deserializing) the property with any of the specified names, but uses the "real" name for writing (serializing).
public class PredictTimeDO {
@JsonAlias("ShipperCode")
private String shipperCode;
@JsonAlias("SendProvince")
private String sendProvince;
@JsonAlias("SendCity")
private String sendCity;
//etc...
}