Java – use Jackson to deserialize arrays
I have a json-rpc client like this, I can't deserialize it
{"value":"xxxx","type":"xxxx"}
Objects I want to deserialize:
@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 properly. If the value is string, but if it is array type, it will throw a jsonmapping exception - unable to start from start_ Deserialize Java. XML in array tag Examples of lang.string are JSON like this:
{\"value\":[8,10],\"type\":\"[int]\"}
The code is:
int[] arr = (int[])getReturnValue(jsonString).getValue();
Getreturnvalue is not special:
ObjectMapper om = new ObjectMapper(); ReturnValue rv = null; rv = om.readValue(json,ReturnValue.class); return rv;
Another problem is that I want the type attribute to be class type, but this throws another mapping exception Jackson has no way to do this, or I have to convert myself from string to appropriate class Thank you for any advice
Solution
Change the constructor to:
@JsonCreator public ReturnValue(@JsonProperty("value") Object val,@JsonProperty("type") String type) {
Because, as the error indicates, it doesn't know how to generate a string from the array However, both string and JSON array can be converted to object; If so, it will be a Java string, or a Java list (for JSON arrays), or a Java map (for JSON objects)