gson 如何在struts 2中从response中排除param并发送我们想要的对象?

ui7jx7zq  于 2023-10-18  发布在  其他
关注(0)|答案(1)|浏览(125)

我想要Ajax请求的JSON结果,但我的要求是只发送对象的ArrayList,并排除action类中存在的一些参数。那么,如何做到这一点?
这是我的行动课

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>

因此,当我检查我的控制台数据返回的行动是有其他变量在它。如何避免这种情况?

6qftjkof

6qftjkof1#

您可以返回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";
}

相关问题