簡體   English   中英

傑克遜中的ObjectMapper錯誤

[英]ObjectMapper error in 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;

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讀取期間不包含屬性的情況下失敗

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM