java 使用 Jackson 反序列化数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5230157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deserialization of arrays with Hymanson
提问by mirekys
i have something like JSON-RPC client, and i′m having trouble deserializing incoming json string into my java object. The incoming json format is:
我有类似 JSON-RPC 客户端的东西,我在将传入的 json 字符串反序列化为我的 java 对象时遇到了麻烦。传入的json格式为:
{"value":"xxxx","type":"xxxx"}
The object i want to deserialize to:
我想反序列化的对象:
@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...
This seems to work ok, if the value is String, but if it′s of array type, it throws JsonMapping Exception - Can not deserialize instance of java.lang.String out of START_ARRAY token for the json like this:
这似乎工作正常,如果值是字符串,但如果它是数组类型,它会抛出 JsonMapping 异常 - 不能像这样从 START_ARRAY 令牌中反序列化 java.lang.String 的实例:
{\"value\":[8, 10], \"type\":\"[int]\"}
The code is:
代码是:
int[] arr = (int[])getReturnValue(jsonString).getValue();
Where getReturnValue is nothing special:
getReturnValue 没有什么特别之处:
ObjectMapper om = new ObjectMapper();
ReturnValue rv = null;
rv = om.readValue(json, ReturnValue.class);
return rv;
The another problem is that i would want the type property to be of Class type, but this would throw another mapping exception. Is there any way in Hymanson to do it, or do i have to convert from string to appropriate class myself. Thank you for any advice.
另一个问题是我希望 type 属性为 Class 类型,但这会引发另一个映射异常。Hyman逊有什么方法可以做到这一点,还是我必须自己从字符串转换为适当的类。谢谢你的任何建议。
回答by StaxMan
Change your constructor to be:
将您的构造函数更改为:
@JsonCreator
public ReturnValue(@JsonProperty("value") Object val, @JsonProperty("type") String type) {
since, like error points out, it does not know how to make a String out of array. But both String and JSON Array can be converted to Object; if so, it'll be Java String, or Java List (for JSON arrays), or Java Map (for JSON objects).
因为,就像错误指出的那样,它不知道如何从数组中生成一个字符串。但是String和JSON Array都可以转为Object;如果是这样,它将是 Java String,或 Java List(对于 JSON 数组)或 Java Map(对于 JSON 对象)。