我想要 Ajax 请求的 JSON 结果,但我的要求是仅发送对象的
ArrayList
并排除操作类中存在的一些参数。那么如何做到这一点?
这是我的动作课
public class AjaxAction{
private int color;
private String prodId;
private List<Product> productList;
public String execute(){
productList= service.getProductList();//this method is getting list of products
HttpServletResponse response = ServletActionContext.getResponse();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(productList,
new TypeToken<List<Product>>() {
}.getType());
JsonArray jsonArray = element.getAsJsonArray();
response.setContentType("application/json");
try {
response.getWriter().print(jsonArray);
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
我的
struts.xml
文件是:
<package name="json" namespace="/" extends="json-default">
<interceptors>
<interceptor-stack name="mystack">
<interceptor-ref name="defaultStack" />
<interceptor-ref name="json">
<param name="enableSMD">true</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="getProduct" class="com.xyz.action.AjaxAction">
<result name="success" type="json" />
<param name="root">productList</param>
</action>
</package>
因此,当我检查从操作返回的控制台数据中是否有其他变量。如何避免这种情况?
您可以返回
stream
结果
<action name="getProduct" class="com.xyz.action.AjaxAction">
<result name="success" type="stream">
<param name="contentType">application/json</param>
</result>
</action>
并在行动中
private InputStream inputStream;
//getter here
public InputStream getInputStream () {
return inputStream;
}
public String execute(){
productList= service.getProductList();//this method is getting list of products
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(productList,
new TypeToken<List<Product>>() {
}.getType());
JsonArray jsonArray = element.getAsJsonArray();
inputStream = new ByteArrayInputStream(jsonArray.toString().getBytes());
return "success";
}