<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="default" namespace="/"
extends="struts-default, json-default">
<action name="getDataAction" class="DataAction">
<result name="success" type="json">
<param name="root">root</param>
</result>
</action>
</package>
</struts>
struts配置 返回类型是json
import com.opensymphony.xwork2.ActionSupport;
public class DataAction extends ActionSupport {
private String root;
/**
* @return
*/
public String execute() {
root = "hello word";
return SUCCESS;
}
public String getRoot() {
return root;
}
public void setRoot(String root) {
this.root = root;
}
}
http://localhost:8090/jsondemo/getDataAction.action
浏览器返回“hello word”
----------------------------------------------------_____________________________________________________________________---------------------------------
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import com.opensymphony.xwork2.ActionSupport;
public class DataAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private JSONObject root;
/**
* @return
*/
public String execute() {
Map<String, String> respond = new HashMap<String, String>();
respond.put("a", "hello a");
respond.put("b", "hello b");
respond.put("c", "hello c");
root=JSONObject.fromObject(respond);
System.out.println(root.toString());
return SUCCESS;
}
public JSONObject getRoot() {
return root;
}
public void setRoot(JSONObject root) {
this.root = root;
}
}
浏览器返回
{"b":"hello b","c":"hello c","a":"hello a"}