如何在SpringMVC中为某个类自定义JSON [英] How to customize the JSON for a certain class in SpringMVC
问题描述
我正在使用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 $上使用Jackson的
@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屋!