如何在SpringMVC中为某个类自定义JSON [英] How to customize the JSON for a certain class in SpringMVC

查看:156
本文介绍了如何在SpringMVC中为某个类自定义JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SpringMVC并使用以下方法。

I'm using SpringMVC and have the following Method.

@RequestMapping("/login")
public @ResponseBody User login(User user) {
    // some operation here ....
    return user;
}

在大多数情况下,SpringMVC以适当的方式将对象转换为JSON。但有时您可能需要自定义JSON。我在哪里可以为所有User对象自定义JSON。我希望将User对象转换为JSON的行为全面一致。我猜一个监听器或接口可以实现这一点。这种解决方案是否存在?

In most cases, SpringMVC converts an object to JSON in a proper manner. However sometimes you might need to customize the JSON. Where can I customize the JSON for ALL the User object. I want the behavior of converting a User object to JSON to be consistent across the board. I guess a listener or interface can achieve that. Does that kind of solution exist?

PS。如果我想转换的对象是第三方类的实例怎么办?我无法在类定义中自定义它,因为我没有源代码...

PS. What if the Object I wanna convert is an instance of third-party class? I cannot customize it in the class definition because I don't have the source code...

推荐答案

Spring使用Jackson序列化并默认反序列化JSON。您可以在用户类型和提供商 JsonSerializer @JsonSerialize 注释c $ c>实现,可以根据需要执行序列化。

Spring uses Jackson to serialize and deserialize JSON by default. You can use Jackson's @JsonSerialize annotation on your User type and provider a JsonSerializer implementation which performs the serialization as you want it.

这篇关于如何在SpringMVC中为某个类自定义JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆