代码之家  ›  专栏  ›  技术社区  ›  Alberto Favaro

使Jackson解释单值JSON

  •  1
  • Alberto Favaro  · 技术社区  · 7 年前

    我正在寻找解决这个问题的办法,但什么也找不到。

    HttpURLConnection :

    "OK"
    

    乍一看,我认为这种响应是不正确的,因为我总是看到一些键-值对JSON。在我读到杰森一家 can take this form 我学到了:

    enter image description here

    https://jsonlint.com/ 给我一个 尝试验证时的响应 "OK" 如何用Jackson中的这个JSON响应映射Java类(称为RestResponse)?

    JsonMappingException: no single-String constructor/factory method :

    final String json = "OK";
    
    final ObjectMapper mapper = new ObjectMapper()
            .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
    final RestResponse response = mapper.readValue(json, RestResponse.class);
    

    我甚至不知道从哪里开始我的工作 RestResponse 因为它没有像@JsonProperty这样可以用Jackson注释标记的属性。

    有人知道杰克逊为什么不考虑这个案子吗? 还是有别的方法?

    1 回复  |  直到 7 年前
        1
  •  2
  •   dnault    7 年前

    你的 RestResponse 将需要一个接受单个字符串的构造函数。为构造函数添加注释 @JsonCreator .