Reini
Reini

Reputation: 1281

Returning the JSON representation of a String with Jersey

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?

Upvotes: 14

Views: 11771

Answers (3)

Pau
Pau

Reputation: 803

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();
}

Upvotes: 3

SiMet
SiMet

Reputation: 612

You can also return it as:

@GET
@Path("hello/{name}")
@Produces( MediaType.APPLICATION_JSON)
public String hello(@PathParam("name") String name) {
    return "\"Hello " + name + ", it is " + new Date()+'"';
}

but it's look very strange for me.

Creating DTO for every object also looks strange just for one String.

Is there any better option?

Upvotes: 2

basiljames
basiljames

Reputation: 4847

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 {)

Upvotes: 5

Related Questions