【问题标题】:Can not deserialize instance of java.lang.String[] out of VALUE_STRING token无法从 VALUE_STRING 令牌中反序列化 java.lang.String[] 的实例
【发布时间】:2017-08-25 05:05:16
【问题描述】:

无法从 VALUE_STRING 令牌 [...] 中反序列化 java.lang.String[] 的实例(通过引用链:[...].model.User["ethnicities"])

我有一个属性为ethnicities 的用户对象。

据我所知,错误是因为 json“类型”与属性类型不匹配,但在我的情况下两者都是字符串数组。

我做错了吗?

另外,我无法弄清楚VALUE_STRING 在解析中代表什么。

服务器端正在使用 Loopback,并且种族属性定义如下:

"ethnicities": [ "" ]

Android 客户端使用 Jackson 将 json 映射到 pojo,反之亦然。 pojo 中的种族如下所示:

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

到 json 的映射:

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

以及来自 json 的映射:

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

以下是一些传入 json 的示例:

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

"ethnicities": [
  "Caucasian"
]

"ethnicities": null

谢谢!

【问题讨论】:

    标签: java android json jackson


    【解决方案1】:

    尝试将此标志设置为ObjectMapper

    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    

    【讨论】:

    • 不,我已经看到并尝试过,但没有成功。虽然我没有DeserializationFeature,但我通过DeserializationConfig.Feature 访问它,它并不能防止错误。
    【解决方案2】:

    这是您处理的整个 JSON 吗?

    我今天也遇到了类似的问题。当要序列化的属性是 JSON 根属性时,似乎无法将 JSON-Array 反序列化为 Java String[] 或 List。

    最后,我将值包装在另一个对象中。在您的情况下,它可能看起来像:

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

    也许这只是一个配置问题 - 但我不知道如何在不包装数组的情况下处理它。

    希望,这会有所帮助。 丹尼尔

    【讨论】:

      猜你喜欢
      • 2017-03-02
      • 2018-03-30
      • 2015-03-10
      • 2019-06-01
      • 2013-10-23
      • 1970-01-01
      • 2019-12-13
      • 2019-02-08
      • 2017-09-23
      相关资源
      最近更新 更多