Search code examples
jsonspringspring-mvcslingjackson-databind

How to return json data from spring controller in apache sling and neba environment


I am using Neba library along with Apache sling.

Now my spring controller working fine with this code.

@RestController
public class CategoryController {
    @RequestMapping(value = "/category/list", method = RequestMethod.GET)
    public String sayHello() {
        return "Hello World!";
    }
}

after hitting url http://localhost:8080/bin/mvc.do/category/list

I am getting response "Hello World!"

But when I am trying to return List String like this -

@RestController
public class CategoryController {
    @RequestMapping(value = "/category/list", method = RequestMethod.GET)
    public List<String> sayHello() {
        return new Arrays.asList(new String[]{"A","B","C"});
    }
}

I am getting following exception -

java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.Arrays$ArrayList

I do have jackson databind in my library

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.5</version>
        </dependency>

I also checked bundle jar it has these library in lib. Still not sure why it doesn't work. Any help is highly appriciated.


Solution

  • To enable Spring's support for JSON conversion from Controller responses, deploy the jackson-databind, jackson-core, jackson-annotations bundles. Spring then picks up the these bundles (this may require a refresh/restart of Sling) and automatically adds new message converters which use jackson to convert the Objects returned by a @Controller's method to JSON, for example:

    @RestController
    public class CategoryController {
        @RequestMapping(value = "/category/list", method = RequestMethod.GET)
        public List<String> sayHello() {
            return Arrays.asList("A","B","C");
        }
    }
    

    Note: It is really these jackson bundles that must be deployed. The availability of the jackson packages alone would not be enough, as the Spring bundles shipped with NEBA have optional require-bundle (not import-package) dependencies to jackson (see neba-155 for why that is).

    The NEBA sample project now includes the jackson bundles, so you can use it as a starting point to try automatic JSON conversion from controller responses.

    Regarding Tim's comment above, one does not have to convert manually. Spring MVC can do so automatically based on content-negotiation via the request's "Accept" header and the available Spring Message Converters, see $ 28.10.2 HTTP Message Conversion in the Spring Docs.

    Hope that helps!