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

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

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

  1. public class AjaxAction{
  2. private int color;
  3. private String prodId;
  4. private List<Product> productList;
  5. public String execute(){
  6. productList= service.getProductList();//this method is getting list of products
  7. HttpServletResponse response = ServletActionContext.getResponse();
  8. Gson gson = new Gson();
  9. JsonElement element = gson.toJsonTree(productList,
  10. new TypeToken<List<Product>>() {
  11. }.getType());
  12. JsonArray jsonArray = element.getAsJsonArray();
  13. response.setContentType("application/json");
  14. try {
  15. response.getWriter().print(jsonArray);
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }
  19. return "success";
  20. }

我的struts.xml文件是:

  1. <package name="json" namespace="/" extends="json-default">
  2. <interceptors>
  3. <interceptor-stack name="mystack">
  4. <interceptor-ref name="defaultStack" />
  5. <interceptor-ref name="json">
  6. <param name="enableSMD">true</param>
  7. </interceptor-ref>
  8. </interceptor-stack>
  9. </interceptors>
  10. <action name="getProduct" class="com.xyz.action.AjaxAction">
  11. <result name="success" type="json" />
  12. <param name="root">productList</param>
  13. </action>
  14. </package>

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

6qftjkof

6qftjkof1#

您可以返回stream结果

  1. <action name="getProduct" class="com.xyz.action.AjaxAction">
  2. <result name="success" type="stream">
  3. <param name="contentType">application/json</param>
  4. </result>
  5. </action>

在行动中,

  1. private InputStream inputStream;
  2. //getter here
  3. public InputStream getInputStream () {
  4. return inputStream;
  5. }
  6. public String execute(){
  7. productList= service.getProductList();//this method is getting list of products
  8. Gson gson = new Gson();
  9. JsonElement element = gson.toJsonTree(productList,
  10. new TypeToken<List<Product>>() {
  11. }.getType());
  12. JsonArray jsonArray = element.getAsJsonArray();
  13. inputStream = new ByteArrayInputStream(jsonArray.toString().getBytes());
  14. return "success";
  15. }
展开查看全部

相关问题