简体   繁体   中英

JAX-RS + RESTEasy service return JSON String without double quote

I'm new to JAX-RS + RESTEasy

What is impeding me is that the service return the JSON String without double quotes.

@Path("/hello")
public class HelloService {

    @GET
    @Path("say")
    @Produces(MediaType.APPLICATION_JSON)
    public String say() {
        return "Hello";
    }
}

When I call "/hello/say" it just returns Hello but what I'm expecting is "Hello"

Googled for several days. I have a piece of Javascript using JQuery which calls the service like this:

$(function(){
    $.ajax({
            url : "services/hello/say",
            context : $('#message'),
            success : function(data){
                    $(this).html(data);
                },
            error : function(xhr, ajaxOptions, thrownError){
                    $(this).html(xhr.status + "<br>" + thrownError);
                }   
        });
    });

And this is the result

SyntaxError: Unable to parse JSON string

Although the status is 200. Is there a way to solve this rather than manually adding the double quotes to the string ?

Which JSON implementation are you using together with RESTeasy, Jettison or Jackson?


Just tried with Jettison, same problem. I just looked into the JSON specification and from there it is written, that a value itself is not a valid JSON response (see http://www.json.org/ ). Either you have an object or an array of values.

I guess that could be the problem as RESTeasy isn't sure what to do as you don't return an Object moreover a single type (eg String, Integer, ...).

Wonder what happen if one returns an array.

The problem isn't with the framework, but with your code. According to JAX-RS, the method signature public String say() indicates that the String you return from the method is the entity to be returned in the response. No further processing is done. I'd link the relevant docs, but jcp.org, where they used live, appears to be gone. If you want your RESTEasy to do JSON marshalling for you, you need to return a POJO.

I would suggest you to use Jackson JSON provider. You just need to add the resteasy-jackson-provider.jar in your build path of the project. Assign the annotation, @Produces("application/json") to your method in your Business Service. And you are ready to go. Cheers !!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM