ajax 调用后端传递的map类型时

ajax 调用后端传递的map类型时,ajax的接收数据类型是json类型,那就需要把后端map转成json才能接收,

这里用到阿里巴巴的fastjson或者json-lib(比较老了,建议不用)

Map转成json格式 
Map<String,Object> map = new HashMap<String,Object>(); 
map.put("users", users); 
map.put("u", u); 
1.转成JSONArray类型 
JSONArray json = JSONArray.fromObject(map); 
System.out.println(json.toString());// 
[{"users":[{"password":"1234","username":"cxl"},{"password":"1234","username":"lhl"}],"u":{"password":"1234","username":"lhl"}}] 
response.getWriter().print(json.toString); 
js中取数据:alert(data[0].users[0].username); 
2.转成JSONObject类型 
JSONObject json = JSONObject.fromObject(map); 
System.out.println(json);// 
{"user":[{"password":"1234","username":"cxl"},{"password":"1234","username":"lhl"}],"u":{"password":"1234","username":"lhl"}} 
response.getWriter().print(json); 
js中取数据:alert(data.user[0].username); 

这里会出现fromObject(Map<String,Object>) is undefined for the type JSONObject错误

原因就是因为引入包的问题


org.json.JSONObject:

JSONObject json = new JSONObject(str);
  • 1

net.sf.json.JSONObject:

JSONObject json = JSONObject.fromObject(str);
  • 1

net.sf.json.jsonobject 没有 new JSONObject(String)的构造方法


猜你喜欢

转载自blog.csdn.net/jaryle/article/details/78824178