由于输入结束 jackson 解析器,没有要映射的内容

新手上路,请多包涵

我从服务器得到这个响应 {"status":"true","msg":"success"}

我正在尝试使用 Jackson 解析器库解析此 json 字符串,但不知何故我面临映射异常说明

com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
 at [Source: java.io.StringReader@421ea4c0; line: 1, column: 1]

为什么我们会得到这种异常?

如何理解导致此异常的原因?

我正在尝试使用以下方式解析:

 StatusResponses loginValidator = null;

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(Feature.AUTO_CLOSE_SOURCE, true);

try {
    String res = result.getResponseAsString();//{"status":"true","msg":"success"}
    loginValidator = objectMapper.readValue(result.getResponseAsString(), StatusResponses.class);
} catch (Exception e) {
    e.printStackTrace();
}

StatusResponse类

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "status","msg" })
public class StatusResponses {

    @JsonProperty("status")
    public String getStatus() {
        return status;
    }

    @JsonProperty("status")
    public void setStatus(String status) {
        this.status = status;
    }

    @JsonProperty("msg")
    public String getMessage() {
        return message;
    }

    @JsonProperty("msg")
    public void setMessage(String message) {
        this.message = message;
    }

    @JsonProperty("status")
    private String status;

    @JsonProperty("msg")
    private String message;

    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonGetter
    public Map<String, Object> getAdditionalProperties() {
        return additionalProperties;
    }

    @JsonSetter
    public void setAdditionalProperties(Map<String, Object> additionalProperties) {
        this.additionalProperties = additionalProperties;
    }
}

原文由 Swapnil Kadam 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.9k
2 个回答
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.ObjectMapper;

StatusResponses loginValidator = null;

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(Feature.AUTO_CLOSE_SOURCE, true);

try {
    String res = result.getResponseAsString();//{"status":"true","msg":"success"}
    loginValidator = objectMapper.readValue(res, StatusResponses.class);//replaced result.getResponseAsString() with res
} catch (Exception e) {
    e.printStackTrace();
}

不知道它是如何工作的以及为什么会工作? :( 但它奏效了

原文由 Swapnil Kadam 发布,翻译遵循 CC BY-SA 4.0 许可协议

在我的例子中,问题是由我将一个空 InputStream 传递给 ObjectMapper.readValue 调用引起的:

 ObjectMapper objectMapper = ...
InputStream is = null; // The code here was returning null.
Foo foo = objectMapper.readValue(is, Foo.class)

我猜这是导致此异常的最常见原因。

原文由 Farrukh Najmi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题