MayNotBe
MayNotBe

Reputation: 2140

Can not deserialize instance of java.lang.String[] out of VALUE_STRING token

Can not deserialize instance of java.lang.String[] out of VALUE_STRING token [...] (through reference chain: [...].model.User["ethnicities"])

I have a user object with a property ethnicities.

From what I can tell the error is because the json "type" doesn't match the property type but in my case both are String arrays.

Am I doing something wrong?

Also, I can't figure out what VALUE_STRING represents in the parsing.

Server-side is using Loopback and the ethnicities property is defined as such:

"ethnicities": [ "" ]

Android client is using Jackson to map the json to the pojo and vice versa. Ethnicities in pojo looks like this:

private String[] ethnicities;
public String[] getEthnicities() {return ethnicities;}
public void setEthnicities(String[] ethnicities) {this.ethnicities = ethnicities;}

The mapping to json:

try {
    ObjectMapper mapper = new ObjectMapper();
    jsonUserObject = mapper.writeValueAsString(user);
} catch (IOException e) {
    System.out.println("IOException converting user object to JSON");
}

and the mapping from json:

try {
    ObjectMapper mapper = new ObjectMapper();
    user = mapper.readValue(userObjectJSON, User.class);
} catch (IOException e) {
    System.out.println("IOException converting JSON to user object");
}

Here's some examples of incoming json:

"ethnicities": [
      "Asian",
      "American Indian",
      "Hispanic"
    ]

"ethnicities": [
  "Caucasian"
]

"ethnicities": null

Thanks!

Upvotes: 1

Views: 6740

Answers (2)

Dasch33
Dasch33

Reputation: 151

Is that the whole JSON you're handling?

I was facing a similar problem today. It seems, it is not possible to deserialize a JSON-Array to a Java String[] or List when the property to serialize is the JSON root property.

In the end I wrapped the value in another object. In your case it may look like:

"user": {
  "ethnicities": [
    "Asian",
    "American Indian",
    "Hispanic",
  ]
}

Maybe it is just a configuration problem - but I couldn't figure out, how to deal with it yet without wrapping the Array.

Hope, that helps. Daniel

Upvotes: 0

Sachin Gupta
Sachin Gupta

Reputation: 8388

Try setting this flag to ObjectMapper :

mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

Upvotes: 1

Related Questions