我有类似 JSON-RPC 客户端的东西,我无法将传入的 json 字符串反序列化到我的 java 对象中。传入的json格式为:
{"value":"xxxx","type":"xxxx"}
我想反序列化的对象:
@JsonAutoDetect
@JsonDeserialize()
public class ReturnValue {
private Object value;
private String type;
@JsonCreator
public ReturnValue(@JsonProperty("value") String val, @JsonProperty("type") String type) {
value = val;
this.type = type;
}
...getters, setters...
这似乎工作正常,如果值是字符串,但如果它是数组类型,它会抛出 JsonMapping 异常 - 无法将 java.lang.String 的实例从 json 的 START_ARRAY 标记中反序列化,如下所示:
{\"value\":[8, 10], \"type\":\"[int]\"}
代码是:
int[] arr = (int[])getReturnValue(jsonString).getValue();
getReturnValue 没有什么特别之处:
ObjectMapper om = new ObjectMapper();
ReturnValue rv = null;
rv = om.readValue(json, ReturnValue.class);
return rv;
另一个问题是我希望 type 属性是 Class 类型,但这会引发另一个映射异常。杰克逊有没有办法做到这一点,或者我必须自己从字符串转换为适当的类。谢谢你的任何建议。