Reputation: 3258
I am calling an external web-service to get an object as json. This object has a property "value" which is sometimes a String and sometimes an array of Strings.
public class MyClass {
// ... other variables
private String value;
public String getValue() {
return value;
}
@JsonProperty("value")
public void setValue(String value) {
this.value = value;
}
}
Currently, I get an error org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token
complaining about this field. I was wondering if some one could give me a hint on what is the correct way of defining value
in my class.
This is a part of a sample json that I have to deal with:
{
"id": 12016907001,
"type": "Create",
"value": "normal",
"field_name": "priority"
},
{
"id": 12016907011,
"type": "Create",
"value": [
"sample",
"another"
],
"field_name": "tags"
}
Thanks.
-- EDIT
I changed the type of the value to Object and it solved my problem. However, I am still wondering if there is a better way to handle this case.
Upvotes: 2
Views: 3658
Reputation: 911
A simple hack would be to enable DeserializationFeature#ACCEPT_SINGLE_VALUE_AS_ARRAY and then use Daniel's answer. If the web service returns a string, Jackson will turn it into a single-element collection.
EDIT:
If you can't upgrade to Jackson 1.8 or higher to use this feature, you could do something like:
private Collection<String> value;
public Collection<String> getValue() {
return value;
}
public void setValue(Object value) {
if (value instanceof Collection) {
this.value = (Collection<String>) value;
} else {
this.value = Arrays.asList((String) value);
}
}
Upvotes: 8
Reputation: 4975
You can use JsonNode as type for your value. Afterwards you can process your value dependent on the return values of isArray()
(or isValueNode()
). I think that JsonNodes are the most convenient way way to handle raw JSON because they offer a broad functionality beyond those simple checks.
if (value.isArray()) {
// process your array
} else {
// process your string
}
Upvotes: 0
Reputation: 228
value is an array so it can't be converted to a string.
You're java class should be something like the following:
class MyClass
{
public int id;
public String type;
public Collection<String> value;
public String field_name;
}
I'm using public fields for example (this will work fine).
Upvotes: 0