Jackson中的ObjectMapper错误

时间:2014-02-16 18:06:35

标签: java json jackson

我有以下课程:

public class ServletStatus {
    private int ElapsedTime;
    private int TotalBusinessImpressionKeywordFailed;
    private int TotalKeywordStatsFailed;
    private int TotalRecentSearchesFailed;
    private int TotalBusinessImpressionKeywordSaved;
    private int TotalKeywordStatsSaved;
    private int TotalRecentSearchesSaved;

    private String error;

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    // rest of the getters and setters
}

以及以下JSON:

{"error": "Cannot Accept Request. Servlet has been Shut Down.. "}

我试着按如下方式阅读:

        ObjectMapper mapper = new ObjectMapper();
        ServletStatus status = mapper.readValue(in, ServletStatus.class);

        String strResult = String.format("ElapsedTime(ms): %d, TotalBusinessImpressionKeywordFailed %d, TotalRecentSearchesFailed %d, TotalKeywordStatsFailed %d, TotalBusinessImpressionKeywordSaved %d, TotalKeywordStatsSaved %d, TotalRecentSearchesSaved %d, Success %s ", 
        status.getElapsedTime(), status.getTotalBusinessImpressionKeywordFailed(), status.getTotalRecentSearchesFailed(), status.getTotalKeywordStatsFailed(), status.getTotalBusinessImpressionKeywordSaved(), status.getTotalKeywordStatsSaved(), status.getTotalRecentSearchesSaved(), status.getError());

我得到以下异常:

java.io.EOFException: No content to map to Object due to end of input
at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2775)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2718)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1886)
at nightlybusinessstatsrestart.ShutDownBusinessStatsServlet.showdownServlet(ShutDownBusinessStatsServlet.java:38)
at nightlybusinessstatsrestart.NightlyBusinessStatsRestart.main(NightlyBusinessStatsRestart.java:56)
我做错了什么?我的JSON只包含出错的错误字段。但是,在成功的过程中,我得到以下附加字段:

ElapsedTime, TotalBusinessImpressionKeywordFailed, TotalKeywordStatsFailed, TotalRecentSearchesFailed, TotalBusinessImpressionKeywordSaved, TotalKeywordStatsSaved, TotalRecentSearchesSaved;

1 个答案:

答案 0 :(得分:1)

Jackson使用所有属性(字段)为输出生成json,因此当您尝试为Object ServletStatus创建json表示时,您会发现类似的内容:

{
  ElapsedTime:"",
  TotalBusinessImpressionKeywordFailed:"",
  TotalKeywordStatsFailed:"",
  TotalRecentSearchesFailed="",
  .
  .
  .
  error:""
}

如果你只想让json中的错误考虑使用

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)  

或者

public void setSerializationInclusion(JsonSerialize.Inclusion props)
Method that will define global setting of which bean/map properties are to
be included in serialization. 

如果在json read

期间未包含属性,请避免失败
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);