@RequestBody中的Spring Map Enum

时间:2017-07-10 11:01:36

标签: java spring-mvc

在我的控制器中,我创建了一个允许状态更改的端点:

@RequestMapping(value = "{ids}" + "/" + "status", method = RequestMethod.PUT)
public ResponseEntity<Void> changeStatus(@PathVariable final List<Integer> ids,
                                         @NotNull @RequestBody final String status) {
    deviceService.updateStatus(ids, status);
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}

enum看起来像这样:

public enum DeviceStatus {
    ACTIVE, INACTIVE, DELETED, ARCHIVED;

    @JsonCreator
    public static DeviceStatus parseWithValidation(String status) {
        final String upperCaseStatus = status.toUpperCase();
        if (exists(upperCaseStatus)) {
            return DeviceStatus.valueOf(upperCaseStatus);
        } else {
            throw new UnsupportedStatusException();
        }
    }

    private static boolean exists(final String upperCaseStatus) {
        return Arrays.stream(values()).anyMatch(c -> c.name().equals(upperCaseStatus));
    }
}

Device域对象的字段Status类型为DeviceStatus,因此应如何更改状态:

public void updateStatus(final List<Integer> ids, final String status) {
        getByIds(ids).forEach(device -> {
            device.setStatus(status);
            update(device);
        });
    }

但是device.setStatus(status);存在问题。我可以使用parseWithValidation,但它没有意义,因为它已经完成了。有人给我{"status":"INACTIVE"}我应该如何解析这个枚举?

1 个答案:

答案 0 :(得分:2)

编辑:更新见评论

您的请求正文是一个对象,其中一个字段名为status,类型为DeviceStatus,因此您可以使用Device

所以:

class Device {
    // will be validated in the controller
    private String status;
    // getter, setter, etc
}

// with:

public enum DeviceStatus {
    ACTIVE, INACTIVE, DELETED, ARCHIVED;
}
控制器方法签名中的

@RequestBody Foo foo

public ResponseEntity<Void> changeStatus(@PathVariable final List<Integer> ids, @NotNull @RequestBody final Device device) {
    try {
        deviceService.updateStatus(ids, DeviceStatus.valueOf(device.getStatus()));
    } catch(IllegalArgumentException ex) {
        // throw some custom exception. device.getStatus() was invalid
    } catch(NullPointerException ex) {
        // throw some custom exception. device.getStatus() was null
    }
    // ...