开发者

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,
        HttpServletReq开发者_如何学JAVAuest 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


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.


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);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜