简体   繁体   English

如何在SpringMVC中为特定类自定义JSON

[英]How to customize the JSON for a certain class in SpringMVC

I'm using SpringMVC and have the following Method. 我正在使用SpringMVC并具有以下方法。

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

In most cases, SpringMVC converts an object to JSON in a proper manner. 在大多数情况下,SpringMVC以适当的方式将对象转换为JSON。 However sometimes you might need to customize the JSON. 但是有时您可能需要自定义JSON。 Where can I customize the JSON for ALL the User object. 在哪里可以为所有User对象自定义JSON。 I want the behavior of converting a User object to JSON to be consistent across the board. 我希望将User对象转换为JSON的行为在所有方面都保持一致。 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 uses Jackson to serialize and deserialize JSON by default. Spring默认使用Jackson来序列化和反序列化JSON。 You can use Jackson's @JsonSerialize annotation on your User type and provider a JsonSerializer implementation which performs the serialization as you want it. 您可以在User类型上使用Jackson的@JsonSerialize批注,并提供JsonSerializer实现,该实现可根据需要执行序列化。

Below posting an example for deserializing json Array to Arraylist 下面发布了将json数组反序列化为Arraylist的示例

@RequestMapping(value = "/mapJsonObjects", method = RequestMethod.POST)
public static ModelAndView parseJSONObjects(@RequestParam String jsonList,HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    JSONParser parser=new JSONParser();
    ArrayList filteredList = new ArrayList();
   Object obj = parser.parse(jsonList);
   JSONArray newList = (JSONArray)obj;
   filteredList = newList;
              -----------

} }

To convert an array List to json array. 将数组List转换为json数组。 First add the below beans to springServlet.xml 首先将以下bean添加到springServlet.xml

<bean name="jsonView"
    class="org.springframework.web.servlet.view.json.JsonView">
    <property name="contentType">
        <value>text/html</value>
    </property>
</bean>

Then from the controller return the arraylist as below 然后从控制器返回arraylist,如下所示

                Map<String, Object> filteredMap = new LinkedHashMap<String, Object>();
                List<Accountdb> filteredList;
                ------filteredMap logic -----------
            filteredAccountMap.put("rows", filteredList);
            return new ModelAndView("jsonView", filteredMap);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM