这是JSON 所依赖的JAR包,一定要严格按照版本,特别是STRUTS2-JSON-PLUGIN-2.3.16这个JAR包,此版本对应struts2.3.16,此JAR包见附件。
web.xml配置
<package name="mvinfo" extends="abstract_struts,json-default" namespace="/mvinfo">
<action name="searchJson" class="mvInfoAction" method="searchJson">
<result type="json">
<param name="root">result<!-- result是action中设置的变量名,也是页面需要返回的数据,该变量必须有setter和getter方法 --></param>
</result>
</action>
action 部分(result需要添加set.get方法)
public String searchJson(){
String ss = getRequest().getParameter("keyword");
mcps.clear();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("title", "yinlu1");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("title", "yinlu2");
Map<String, String> map3 = new HashMap<String, String>();
map3.put("title", "yinlu3");
List listtest = new ArrayList();
listtest.add(map1);
listtest.add(map2);
listtest.add(map3);
// 将要返回的map对象进行json处理
JSONArray json = JSONArray.fromObject(listtest);
// 调用json对象的toString方法转换为字符串然后赋值给result
this.result = json.toString();
// 可以测试一下result
System.out.println(this.result);
return SUCCESS;
}
JSP部分:
需要对JSON解析:var result = eval("("+result+")"); //包数据解析为json 格式