ObjectMapper不接受HttpURLConnection的JSON响应

时间:2018-11-15 01:20:52

标签: java json jackson objectmapper

在读取从JSON构建的BufferedReader字符串并尝试将值分配给POJO类时出现问题。

当我使用这种格式时会起作用(偶然发现。复制粘贴):

String build = {\"feature\":{\"id\":\"888888\",\"name\":\"A9 Refresh Release\"}

但是实际上,当从BufferedReader中读取内容时,它看起来像下面的样子:-

{"feature":{"id":"888888","name":"A9 Refresh Release"}}

这是我的代码:

    BufferedReader in = new BufferedReader(newInputStreamReader(connection.getInputStream()));
    StringBuilder build = new StringBuilder();
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
         build.append(inputLine); }
    in.close();
ObjectMapper mapper = new ObjectMapper();
Feature wrap = mapper.readValue(build, Feature.class);

我的问题不是我不知道如何将JSON字符串编组到POJO,而是从HttpURLConnection获得的JSON响应对于ObjectMapper无效。

2 个答案:

答案 0 :(得分:0)

实际上,您必须首先将JSON字符串解析为Jackson JsonNode

public <T> T readValue(JsonParser jp,
              Class<T> valueType)
            throws IOException,
                   JsonParseException,
                   JsonMappingException

将JSON内容反序列化为非容器类型(但是可以是数组类型)的方法:通常是bean,数组或包装器类型(例如Boolean)。

注意:如果结果类型是容器(集合或映射),则不应使用此方法。原因是由于类型擦除,使用此方法时无法自省键和值类型

最终,有两种解决您的问题的方法,如下所示:-

1。快速解析:-

BufferedReader in = new BufferedReader(newInputStreamReader(connection.getInputStream()));
    StringBuilder build = new StringBuilder();
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
         build.append(inputLine); }
         in.close();
    ObjectMapper mapper = new ObjectMapper();
    Feature wrap = mapper.readValue(mapper.readTree(build), Feature.class);

2。低级解析:-

BufferedReader in = new BufferedReader(newInputStreamReader(connection.getInputStream()));
    StringBuilder build = new StringBuilder();
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
         build.append(inputLine); }
         in.close();
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getFactory();
    JsonParser parser = factory.createParser(build);
    Feature wrap = mapper.readValue(mapper.readTree(parser), Feature.class);

答案 1 :(得分:-1)

我发现了我的问题。声明的ObjectMapper.readValue(Sting a, valyetype)仅接受字符串。我正在发送StringBuilderStringBuilder不会格式化我的JSON,但String会格式化。简单修复

Feature wrap = mapper.readValue(build.toString(), Feature.class);