0

我正在使用带有以下代码库的 Spring 休息:

当我通过在请求正文中传递字符串值来调用 /info 时,如果我的后端数据库中不存在此值,我期待以下响应。

{"output":-10} 

但相反,它返回以下响应:

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

谁能告诉我如何摆脱这个 id 默认值?如果 JSON 映射器中有一个布尔变量,那么它也将返回为

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

谁能告诉我如何摆脱这个默认值?

控制器.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);
}

我的服务.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);
}

视图.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
    .....

}
4

1 回答 1

0

使用 Integer 类而不是 int 原始类型。原始类型始终保存默认值,其中类类型默认为 null。

于 2013-01-22T04:04:54.613 回答