[英]Using @JsonAnyGetter /@JsonAnySetter to Serialize JSON and change property name (Jackson)
[英]Change JSON property name on derived classes using Jackson library
我正在使用 Spring 開發新的 REST API,我有BaseResponse
class 作為所有響應的基本響應。 這個 class 包含屬性String requestUuid;
在某些情況下,此requestUuid
必須使用屬性名稱requestUuid
進行序列化,在其他情況下,它必須序列化為request_uuid
,我知道我可以使用@JsonProperty
作為字段級注釋,但它會影響所有響應。 有什么方法可以專門為每個派生類覆蓋屬性名稱。
您可以在方法級別使用@JsonProperty
。 這樣,您可以在子類中重寫字段的getter方法並對其進行注釋。
例如:
class BaseResponse {
private String requestUuid;
public getRequestUuid() {
return requestUuid;
}
}
class OtherResponse extends BaseResponse {
@Override
@JsonProperty("request_uuid")
public getRequestUuid() {
return super.getRequestUuid();
}
}
您可以使用不同的鍵名兩次發送該字段。
@JsonAnyGetter
public Map<String, Object> otherFields() {
Map<String, Object> otherFields = new HashMap<>();
otherFields.put("requestUuid", this.requestUuid);
otherFields.put("request_uuid", this.requestUuid);
return otherFields;
}
另外,請忽略您的實際字段:
@JsonIgnore
private String requestUuid;
擴展@JoshA 響應,另一種選擇是定義一個構造函數並對其進行注釋。 通過避免重寫派生類中的 getter 方法,可以使代碼更簡潔。
class BaseResponse {
private String firstName;
private String lastName;
public BaseResponse(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public getFirstName() {
return firstName;
}
public getLastName() {
return lastName;
}
}
class OtherResponse extends BaseResponse {
public OtherResponse(@JsonProperty("given_name") String firstName, @JsonProperty("family_name") String lastName) {
super(firstName, lastName);
}
}
不,這不可能,您可以為不同類型的請求創建新類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.