Reputation: 2479
i have a rest controller in a spring boot mvc container
@RestController
public class LoginController {
@RequestMapping("rest/login")
public Response login() {
return Response.GRANTED;
}
public static enum Response {
GRANTED, DENIED;
}
}
I have to use double quotes for checking the return type after request a rest resource. how to avoid the double quotes?
$http.post("rest/login", $scope.data).success(function(data) {
if (data === "\"GRANTED\"") {
alert("GRANTED")
} else if (data === "DENIED") {
alert("DENIED")
};
@RestController public class LoginController {
@RequestMapping("rest/login")
public String login() {
return Response.GRANTED.name();
}
public static enum Response {
GRANTED, DENIED;
}
}
bring the result I want but I want the type safe return type Response and not String.
Thanks for help.
Upvotes: 1
Views: 1983
Reputation: 279990
A @RestController
is like a @Controller
annotated with @ResponseBody
. That is, each handler is implicitly annotated with @ResponseBody
. With any reference type other than String
(and a few others), the default target content-type is JSON.
The 6 data types in JSON are Object, Array, Number, String, true, false, and null. How would you map an enum
constant? The default that Jackson (which backs the default JSON HttpMessageConverter
) serializes an enum
constant to a JSON String. That's arguably the best matching JSON data type.
You could force it to write the value without quotes by providing your own JsonSerializer
@JsonSerialize(using = ResponseSerializer.class)
public static enum Response {
...
class ResponseSerializer extends JsonSerializer<Response> {
@Override
public void serialize(Response value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeRaw(value.name());
}
}
but I don't recommend it since you wouldn't be producing valid JSON.
You should really consider what others have suggested and use the various HTTP status codes.
Upvotes: 1