最近学习extjs4,服务器端用springmvc,但在springmvc解析extjs传来的json数据时总是找不到好的解决办法
录我进行指添加或指修改时,往后台传的json数据如下(取名为jsonStr)
{"records": [{"id":"dfds","name":"fsdf","email":"sdf34ds"},
{"id":"dfdsf","name":"fsdf","email":"sdf334ds"}]}
本来想让后台springmvc在controller类的方法参数中使用@RequestBody自动解析成java对象的集合:List<User> 。可总是不能如愿,如果我extjs向后台传送的json数组没有records,只是单纯的{[{"id":"dfds","name":"fsdf","email":"sdf34ds"},
{"id":"dfdsf","name":"fsdf","email":"sdf334ds"}]}
则可用@RequestBody List<User> 处理。后台想到直接把前台传进的json数据当成字符串手动解析,也比较麻烦
代码:
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(jsonStr,Map.class);
也不能直接转换为List<User> ,因为map.get(key)得到的只是List<LinkedHashMap>而不是User对象集合,
后来想到用JsonNode, 一个一个地斌值,代码如下:
ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = null; try { rootNode = objectMapper.readValue(records, JsonNode.class); JsonNode recordsNode = rootNode.path("records"); } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // // System.out.println("recordsNode==>"+recordsNode); List<String> names = recordsNode.findValuesAsText("name"); List<String> emails = recordsNode.findValuesAsText("email"); List<String> ids = recordsNode.findValuesAsText("id"); for(int i=0; i<ids.size(); i++){ User user = new User(); user.setId(System.currentTimeMillis()+""); user.setName(names.get(i)); user.setEmail(emails.get(i)); data.add(user);
貌似太繁锁了
后来google一下,有位老兄说可以这样配置
public @ResponseBody String create(@RequestBody EntityData<User> datas);
EntityData的代码如下:package com.wanghaisheng.controller;
import java.util.List; public class EntityData<T> { private List<T> records; public List<T> getRecords() { return records; } public void setRecords(List<T> records) { this.records = records; } }
一切OK,spring真的太智能了。
不过,看似我错了,自动装配后,此时List中的对象好像还是LinkedHashMap而不是User对象