Reputation: 6121
I have and angular app and I want to make a small session store for the case when a user has to login but should be able to resume where he left the page.
The Storing part is pretty easy since I store the received jsonstring as it is. But when I retun the value the String got escaped to be a string instead of a json. Is there a way to return a string (which is already json) as json object?
@Path("/session")
public class SessionStore extends Application {
@POST
@Path("/save/{variable}")
@Consumes("application/json")
public boolean save(@PathParam("variable") String var, String json) throws Exception {
getSession().setAttribute(var, json);
return true;
}
@GET
@Path("/load/{variable}")
@Produces("application/json")
public Object load(@PathParam("variable") String var) {
return getSession().getAttribute(var); // this string is already a json
}
}
Upvotes: 0
Views: 2967
Reputation: 10961
I don't know which JSON serializer you are using. I could not reproduce this behavior with Jackson.
At first I would change the return time of your method to String. As it does not make sense to convert a String to a JSON-String unless it is already a JSON-String your JSON serializer should not touch it. If it tries to be smarter you can register a custom MessageBodyWriter for Strings:
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JsonStringSerializer implements MessageBodyWriter<String> {
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return type == String.class;
}
@Override
public long getSize(String t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
public void writeTo(String entity, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
entityStream.write(entity.getBytes(Charset.forName("UTF-8")));
}
}
I'd strongly recommend not to change the @Produces
annotation to text/plain
. This may result in returning the correct content but will also change the Content-Type
header to text/plain
. So you are sending JSON but telling your client that it is no JSON. If the client believes you he will not parse the content any more.
Upvotes: 0
Reputation: 3510
If you dont't want your return value to be automatically boxed into the json format, tell your JAX-RS implementation to return plain text instead of json with @Produces("text/plain")
.
@GET
@Path("/load/{variable}")
@Produces("text/plain")
public String load(@PathParam("variable") String var) {
//the cast may not be necessary, but this way your intention is clearer
return (String) getSession().getAttribute(var);
}
Upvotes: 1