我已经定义了JSON Pojo类,如下所示,在下面的MyMessage类中,有时我接收kpMessage类作为字符串,如何将接收到的字符串转换为object。
@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
对象
答案 0 :(得分:0)
对于这个用例,我发现的一个解决方案是按照错误消息的建议进行操作,并创建一个带有单个字符串参数的构造函数;然后使用 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;
}
参考:Convert JSON String (Which includes different lenients) to Java Class with RestTemplate
另一种方法是使用 JsonDeserialize.