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

2022-08-31 10:36:03

我从服务器收到此响应{"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();
}

状态响应类

@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;
    }
}

答案 1
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();
}

不知道它是如何工作的,为什么它工作?:(但它工作


答案 2

在我的情况下,问题是由于我将空输入流传递给 ObjectMapper.readValue 调用引起的:

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

我猜这是这个例外的最常见原因。