开发者

Spring MVC controller how to add custom interceptor for json to object serialization and deserialization

I am using spring 3 MVC with annotation

Using @ResponseBody and @RequestBody annotation开发者_StackOverflow中文版s I am able to serialize and deserialize object to json and vice versa using MappingJacksonHttpMessageConverter.

I need to introduce custom interceptor for object to json conversion which can use compacted keys for example fullName can be used as fN, etc. Can someone suggest me how to embed custom interceptor in controller (using any annotations) for both doing serialization and deserialization.


You can always use any serializer and send it to HTTP stream:

it will make your live easier.

@RequestMapping(value="/get/{id}",method = RequestMethod.GET)
@ResponseBody
public void getData(@PathVariable String id,HttpServletResponse response){

//make our business logic. 

//use any serializer to serialize.
String serialiedObject = Serializer.serialize(Object);
 response.setContentType("application/json");
 response.setContentLength(serialiedObject.length);
 ServletOutputStream out;
try {
    out = response.getOutputStream();
    out.write(serialiedObject);
    out.lose();
    } catch (IOException e) {
    e.printStackTrace();
    }

}

The same way you can get your json string to controller using POST request.

@RequestMapping(value="/add",method = RequestMethod.POST)
@ResponseBody
public void addtData(@RequestParam("json") String myJson){

Object =    //use any serializer to serialize.
Object deSerialiedObject = Serializer.deserialize(myJson);

}

Hope it helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜