2016-08-24 89 views
1

我使用SpringMVC 4.2.5,並使一個休息控制器,但響應不是我想要的。 這是細節。 我有一個實體命名propertyEntitySpringMVC的響應JSON不正確的布爾屬性

public class PropertyEntity implements Serializable, Cloneable { 
    private static final long serialVersionUID = -7032855749875735832L; 
    private int id; 
    private String propertyName; 
    private boolean isEnable; 
    private boolean isDimension; 
    private boolean isMetric; 
} 

和控制器是:

@Controller 
@RequestMapping("/api/v1/properties") 
public class PropertyController { 
    @RequestMapping(method = RequestMethod.GET, 
       produces = "application/json;charset=utf-8") 
    @ResponseStatus(HttpStatus.OK) 
    public @ResponseBody 
    List<PropertyEntity> getAll() { 
     return propertyService.getAll(); 
    } 
} 

當我請求API,其結果是:

[ 
    { 
     "id": 1, 
     "propertyName": "money1", 
     "isEnable": true, 
     "dimension": false, 
     "metric": true 
    }, 
    { 
     "id": 2, 
     "propertyName": "money2", 
     "isEnable": true, 
     "dimension": false, 
     "metric": true 
    } 
] 

我想要的是:

[ 
    { 
     "id": 1, 
     "propertyName": "money1", 
     "isEnable": true, 
     "isDimension": false, 
     "isMetric": true 
    }, 
    { 
     "id": 2, 
     "propertyName": "money2", 
     "isEnable": true, 
     "isDimension": false, 
     "isMetric": true 
    } 
] 

意想不到的是: isDimention更改爲dimension, isMetric更改爲metric, 但isEnable是正確的。

+1

嘗試在場上使用@JsonProperty(「isEnable」) – Naruto

+0

奇怪。如果只有其中一個屬性表現如此,那麼這看起來像是一個錯誤。 – dbreaux

回答

0

我假設你正在使用傑克遜的 「PropertyEntity」 對象轉換爲JSON。

可能的問題可能是PropertyEntity類中的getter和setter。

isEnable的的getter/setter和遵守相似的命名約定isMetric & isDimension

確保布爾開始與isIsMetric()...代替getIsMetric()的干將。

如果這沒有幫助,請在此處分享您的獲得者和安裝者。

+0

是的,這是getters和setters方法的名稱,更改爲getIsMetric()和setIsMetric(boolean isMetric)解決了問題。謝謝! –

0

更改類:

public class PropertyEntity implements Serializable, Cloneable { 
    ... 
    ... 
    @JsonProperty("isEnable") 
    private boolean isEnable; 
    ... 
    ... 
} 

參見:When is the @JsonProperty property used and what is it used for?

+0

我試着添加@JsonProperty(「isMetric」),是的,它結果是'isMetric'結果,但是'metric'仍然存在,所以我認爲原因是@ishanbakshi說的。感謝所有相同的,併爲有用的鏈接。 –