[英]Jackson Deserialize property value with raw json to object
我已經定義了 JSON Pojo 類,如下所示,在下面的 MyMessage 類中,有時我將 kpMessage 類作為字符串接收,如何將接收到的字符串轉換為對象。
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "kp.message", "kp.version" })
public class MyMessage {
@JsonProperty("kp.message")
private KpMessage kpMessage;
@JsonProperty("kp.version")
private String kpVersion;
@JsonProperty("kp.message")
public KpMessage getKpMessage() {
return KpMessage;
}
@JsonSetter
public void setKpMessage(KpMessage kpMessage) {
this.kpMessage = kpMessage;
}
@JsonProperty("kp.version")
public String getKpVersion() {
return kpVersion;
}
@JsonProperty("kp.version")
public void setKpVersion(String kpVersion) {
this.kpVersion = kpVersion;
}
}
KpMessage.java
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "domain", "request_id", "auth_token"})
public class KpMessage {
@JsonProperty("domain")
private Object domain;
@JsonProperty("request_id")
private String requestId;
@JsonProperty("auth_token")
private String authToken;
@JsonProperty("domain")
public Object getDomain() {
return domain;
}
@JsonProperty("domain")
public void setDomain(Object domain) {
this.domain = domain;
}
@JsonProperty("request_id")
public String getRequestId() {
return requestId;
}
@JsonProperty("request_id")
public void setRequestId(String requestId) {
this.requestId = requestId;
}
@JsonProperty("auth_token")
public String getAuthToken() {
return authToken;
}
@JsonProperty("auth_token")
public void setAuthToken(String contextAuthToken) {
this.authToken = authToken;
}
}
下面的示例輸入按預期工作。
{
"kp.message":{
"domain":null,
"request_id":"req-11ef0ffa-0180-4040-a47e-9f78b23b49e9",
"auth_token":"gAAAA"
},
"kp.version":"2.0"
}
然而,下面的輸入失敗,錯誤no String-argument constructor/factory method to deserialize from String value
{
"kp.message": "{
\"domain\": null,
\"request_id\": \"req-11ef0ffa-0180-4040-a47e-9f78b23b49e9\",
\"auth_token\": \"gAAAA\",
}",
"kp.version": "2.0"
}
如何為上述輸入添加反序列化器,以便如果由於轉義字符"
接收到字符串,則將該字符串轉換為KpMessage
對象
對於這個用例,我發現的一個解決方案是按照錯誤消息的建議進行操作,並創建一個帶有單個字符串參數的構造函數; 然后使用 Jackson 或 Gson 解析原始值。 就像是:
public KpMessage(String json) throws IOException {
KpMessage k = new ObjectMapper().readValue(json, KpMessage.class);
this.domain = k.domain;
this.requestId = k.requestId;
this.authToken = k.authToken;
}
參考:使用 RestTemplate 將 JSON 字符串(包括不同的寬大)轉換為 Java 類
另一種方法是使用JsonDeserialize。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.