2016-07-13 50 views
1

當我休息班時,我收到了下面的回覆。Json的響應值沒有設置到Bean類

響應:

 { 
      "_index": "a_index", 
"total":9, 
      "_type": "e", 
      "_id": "BSKnamtd_8-egMNvh", 
      "_data": 2.076404564, 
      "_secure": { 
       "email": "[email protected]" 
      } 
      } 

要設置該響應。如圖所示,我創建了pojo類。

public class data implements Serializable { 

    private static final long serialVersionUID = 644188100766481108L; 
    private String _index; 
    private Integer total; 
    private String _type; 
    private String _id; 
    private Double _data; 
    private Source _secure; 

    public String getIndex() { 
     return _index; 
    } 

    public void setIndex(String _index) { 
     this._index = _index; 
    } 

    public Integer getTotal() { 
     return total; 
    } 

    public void setTotal(Integer total) { 
     this.total = total; 
    } 

    public String getType() { 
     return _type; 
    } 

    public void setType(String _type) { 
     this._type = _type; 
    } 

    public String getId() { 
     return _id; 
    } 

    public void setId(String _id) { 
     this._id = _id; 
    } 

    public Double getData() { 
     return _data; 
    } 

    public void setData(Double _data) { 
     this._data = _data; 
    } 

    public Source getSecure() { 
     return _secure; 
    } 

    public void setSecure(Source _secure) { 
     this._secure = _secure; 

    } 

} 

當我打了電話RESTClient實現,我只得到「全部」剩餘價值得到儘可能空值。 「total」變量沒有下劃線(「」)其餘變量有「」,這樣我就面臨着問題..?

請幫助如何解決這個問題。

+0

運氣好的話這個這麼遠? –

回答

0

JSON對象是

... 
"_index": "a_index", 
"total":9, 
... 

而對於這兩個屬性的屬性是:

public void setIndex(String _index) { 
     this._index = _index; 
    } 

public void setTotal(Integer total) { 
     this.total = total; 
    } 

正如你所看到的,對於的Json _index屬性Java屬性索引(setIndex)

指數_index不同,所以當JSON對象映射它變得無效,因爲它無法找到物業_index。

在你有對Json的總資產Java屬性總(setTotal)另一方面。

在這種情況下,Json和Java中的屬性具有相同的名稱,所以它獲取加載的值。

0

Java類屬性名稱對對象映射器不可見(它是private)。你的情況重要的是getter/setter的名字。它用於將JSON對象屬性名稱映射到Java類(POJO)。

你有兩個我能想到的選擇。骯髒一個僅僅是制定者的姓名改爲set_index()set_type()等使它們對應於JSON屬性名稱,或者您也可以這樣做的權利:

  1. Java類的屬性更改名稱和方法標準約定,以便代碼是很好,readabl。
  2. 使用@JsonProperty註釋屬性來表示不同的JSON和Java對象之間的默認映射。

從註釋類型JsonProperty Java文檔:

缺省值(「」)表示該字段名被用作 屬性名沒有任何修改,但它可以被指定爲 非空值來指定不同的名稱。屬性名稱是指外部使用的 名稱,作爲JSON對象中的字段名稱。

例與註釋:

public class test { 

    @JsonProperty("_index") 
    private String index; 

    private Integer total; 

    @JsonProperty("_type") 
    private String type; 

    public String getIndex() { return index; } 
    public void setIndex(String index){ this.index = index; } 

    public Integer getTotal() { ... } 
    public void setTotal(Integer total) { ... } 

    public String getType() { ... } 
    public void setType(String type) { ... } 
    .... 
}