I'm about to setup a REST-Webservice with Jersey. At the moment I am a bit confused about the correct representation of Strings or other Value types in JSON. Here are two snippets:
@GET
@Path("user")
@Produces( MediaType.APPLICATION_JSON)
public User user() {
return new User("reini", "admin");
}
Calling this method in a Browser will display a "good" JSON String like that:
{"name":"reini","role":"admin"}
My second method looks like this:
@GET
@Path("hello/{name}")
@Produces( MediaType.APPLICATION_JSON)
public String hello(@PathParam("name") String name) {
return "Hello " + name + ", it is " + new Date();
}
Calling that method in a Browswer will display a pure String without any JSON-Stuff (Curly Braces etc):
Hello firefox, it is Tue Sep 18 13:52:57 CEST 2012
I want to consume this service with the dojo toolkit. The problem is, that I get an for the second method as soon as I set [handleAs: "json"]-flag. It throws me an error "SyntaxError: Unexpected token H" where "H" is the first letter of the returned string.
So: What is the correct json representation of Strings and other value types and what annotations I have to set for my method to produce these?
You should define a DTO
and put your String
in that. So you will hava a HelloResp
class with one String as attribute. In your method populate that attribute and return.
You can check this Tutorial. Another tutorial.
Firefox is not showing error because, it is not processing your response. Whatever is returned by service is displayed. The toolkit however starts processing the reponse as a JSON but did not a valid JSON (JSON starts with {
)
If you are returning a String why do you define it as a type JSON?
Just return it as a plain text (MediaType.TEXT_PLAIN):
@GET
@Path("hello/{name}")
@Produces( MediaType.TEXT_PLAIN)
public String hello(@PathParam("name") String name) {
return "Hello " + name + ", it is " + new Date();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With