Jan
Jan

Reputation: 2833

How to handly arbitrary json objects with spring mvc?

I successfully use spring-mvc with json in order to convert between domain objects and json objects.

Now, I want to write a Controller that just accepts any json, validates it and provides it in a compact serialisable form for the service layer. (The json string would be sufficient, any compact byte array representation better). My current approch is this:

@RequestMapping(value="/{key}", method=RequestMethod.GET)
@ResponseBody
public Object getDocument(@PathVariable("username") String username,
        @PathVariable("key") String key,
        HttpServletRequest request,
        HttpServletResponse response) {
    LOGGER.info(createAccessLog(request));
    Container doc = containerService.get(username, key);
    return jacksonmapper.map(doc.getDocument(), Map.class);
}

and

@RequestMapping(value="/{key}", method=RequestMethod.PUT)
public void putDocument(@PathVariable("username") String username,
        @PathVariable("key") String key,
        @RequestBody Map<String,Object> document,
        HttpServletRequest request,
        HttpServletResponse response) {
    LOGGER.info(createAccessLog(request));
    containerService.createOrUpdate(username, key,document);
}

Note that this approach does not work because I don't want a Map in the put method and the get method returns just {"this":null};. How do I have to configure my methods?

Cheers,

Jan

Upvotes: 0

Views: 2106

Answers (2)

Md. Arafat Al Mahmud
Md. Arafat Al Mahmud

Reputation: 3214

Its easy. You don't need the @RequestBody annotation.

    @RequestMapping(value="/{key}", method=RequestMethod.PUT)
    public void putDocument(@PathVariable("username") String username,
            @PathVariable("key") String key, HttpServletRequest request, HttpServletResponse response) {

        try {
            String jsonString = IOUtils.toString(request.getInputStream()); 
        } catch (IOException e) {
            e.printStackTrace();
        }

        LOGGER.info(createAccessLog(request));
        containerService.createOrUpdate(username, key,document);
    }

Upvotes: 0

Bozho
Bozho

Reputation: 597124

Spring has this functionality automatically. You just need <mvc:annotation-driven /> and jackson on your classpath. Then spring will handle all requests with accept header set to */json, and respective responses, through the JSON mapper.

Upvotes: 2

Related Questions