2013-01-22 31 views
0

我使用彈簧安置與下面的代碼庫:入門春季休息擺脫默認值

當我調用通過請求體傳遞字符串值/信息,我期待下面的響應如果此值不存在於我的後端數據庫中。

{"output":-10} 

,而是它返回我下面迴應:

{"id": 0, "output":-10} 

任何一個可以告訴我如何擺脫這個ID默認值嗎?如果在JSON映射布爾變量,那麼這也將得到返回

{"id": 0, "booleanVar": false, "output":-10} 

任何一個可以告訴我如何擺脫這個默認值嗎?

Controller.java

@RequestMapping(value = "heartbeat", method = RequestMethod.GET, consumes="application/json") 
public ResponseEntity<String> getHeartBeat() throws Exception { 
    String curr_time = myService.getCurrentTime();  
    return MyServiceUtil.getResponse(curr_time, HttpStatus.OK); 
} 

@RequestMapping(value = "info", method = RequestMethod.POST, consumes="application/json") 
public ResponseEntity<String> getData(@RequestBody String body) throws Exception { 
    .... 
    myInfo = myService.getMyInfo(myServiceJson); 
    return MyServiceUtil.getResponse(myInfo, responseHeader, HttpStatus.OK); 
} 

MyService.java

@Override 
public String getCurrentTime() throws Exception { 
    String currentDateTime = null; 
    MyServiceJson json = new MyServiceJson(); 
    ObjectMapper mapper = new ObjectMapper().configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false); 

    try {   
     Date currDate = new Date(System.currentTimeMillis()); 
     currentDateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(currDate);   
     json.setCurrentDateTime(currentDateTime); 

     ObjectWriter writer = mapper.writerWithView(Views.HeartBeatAPI.class); 
     return writer.writeValueAsString(json); 

    } catch (Exception e) { 
     throw new Exception("Excpetion in getCurrentTime: ", HttpStatus.BAD_REQUEST);   
    } 
} 

@Override 
public String getMyInfo(MyServiceJson myServiceJson) throws Exception {    
    MyServiceJson json = new MyServiceJson(); 
    json.setFirstName("hhh"); 
    json.setLastName("abc"); 

    ObjectMapper mapper = new ObjectMapper(); 
    return mapper.writeValueAsString(json); 
} 

Views.java

public class Views { 
    public static class HeartBeatAPI { } 
} 

MyServiceJson.java

@JsonSerialize(include = Inclusion.NON_NULL) 
public class MyServiceJson { 
    private int id; 
    private String firstName; 
    private String lastName; 

    @JsonView(Views.HeartBeatAPI.class) 
    private String currentDateTime; 

    // Getter/Setter for the above variables here 
    ..... 

} 
+0

如果你不需要'id',只需在你的MyServiceJson類中刪除它的getter&setter –

+0

刪除id'setter getter將不起作用。用戶不想刪除id屬性,他只希望只有當值集不是默認值時才顯示。 – lokesh

回答

0

使用Integer類而不是int基元類型。原始類型始終保存默認值,其中類類型默認爲null。

+0

我不清楚。你是否建議聲明私人整數ID;而不是私人詮釋編號; ????? –

+0

絕對正確。 – lokesh

+0

也不要忘記更新setter和getter方法。 – lokesh