// 实体类、List、Map等类型转成json类型的String
public static String objectToJson(Object obj) throws JSONException,
IOException {
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(obj);
return jsonStr;
}
JAVA中contrallor层
@ResponseBody
@RequestMapping("/test.do")public String toJson(HttpServletRequest request, Model model) {
JSONObject json = new JSONObject();
Map<String, List<String>> map = new HashMap<String, List<String>>();
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
map.put("key", list);
List<String> list1 = new ArrayList<String>();
list1.add("4");
list1.add("5");
map.put("value", list1);
json.putAll(map);
return json.toString();
}
jsp中js,ajax调用
testJSON();
function testJSON() {
/* var str = '{"key":["1","2","3"],"value":["4","5"]}';
var json = eval("(" + str + ")");
alert(json.key); */
var urlPath = "${ctx}/test.do";
$.ajax({
type : "POST",
url : urlPath,
data : {
},
dataType : "json",
success : function(data) {
var json = eval("(" + data + ")");
alert(json.key);
},
error : function(data) {
alert("error");
}
});
}