How to customize the JSON for a certain class in SpringMVC

前端 未结 2 903
萌比男神i
萌比男神i 2021-01-27 08:09

I\'m using SpringMVC and have the following Method.

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


        
相关标签:
2条回答
  • 2021-01-27 08:52

    Below posting an example for deserializing json Array to 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. First add the below beans to 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

                    Map<String, Object> filteredMap = new LinkedHashMap<String, Object>();
                    List<Accountdb> filteredList;
                    ------filteredMap logic -----------
                filteredAccountMap.put("rows", filteredList);
                return new ModelAndView("jsonView", filteredMap);
    
    0 讨论(0)
  • 2021-01-27 08:59

    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.

    0 讨论(0)
提交回复
热议问题