Last Updated: February 25, 2016
· jack snow

JAX-RS returns Object.toString() instead of JSON

Suppose you have a JAX-B annotated class and you want to return objects of that class in one of your JAX-RS services, but the result is always equal to that of a toString() call on that object. E.g. com.domain.MyClass@1796224 is returned, if you didn’t override toString(). The problem will probably be, that your JAX-RS method is annotated with @Produces("text/plain") instead of @Produces("application/json"), which makes your clever JAX-RS implementation think that it’s more appropriate to return a plain String representation of your object. Here comes a small example:

public class MyClass {
    private String message;
    public MyClass(String message) { this.message = message; }

JAX-RS service method:

public MyClass getMessage() {
    return new MyClass("Hello world!");