执行struts 2动作类时给出一个空的json结果

时间:2015-11-02 02:49:36

标签: java json struts2 struts2-json-plugin struts-action

我试图使用hibernate ORM从数据库中检索数据,并使用Struts2获取输出为json的结果。 一切都可以从数据库中检索数据, 但是对于json结果我只得到{}

我认为我的编码做错了。但需要一些帮助才能搞清楚。

  

这是我的Action类:

@ParentPackage("json-default")
public class SocialIconsAction extends ActionSupport {

    private List<TiendayaCurrencies> _currency;

    public List<TiendayaCurrencies> getCurrency() {
        return _currency;
    }

    public void setCurrency(List<TiendayaCurrencies> _currency) {
        this._currency = _currency;
    }

    @Action(value = "currencies", results = {
        @Result(name = "success", type = "json", params = {"includeProperties",
            "_currency\\[\\d+\\]\\..*"})})
    @Override
    public String execute() {
        _currency = loadCurrencies();

        /*Nothing wrong with the DB results.Just to  test everything works fine.*/
        //for (TiendayaCurrencies _currency1 : _currency) {
           // System.out.println("Title - "+_currency1.getTitle());
       // }


        return SUCCESS;
    }

    private List<TiendayaCurrencies> loadCurrencies() {
        Session session = com.tiendaya.connection.HibernateUtil.
                getSessionFactory().openSession();
        List<TiendayaCurrencies> cList = session.
                createCriteria(TiendayaCurrencies.class).list();

        return cList;
    }
}
  

Pojo课程:

public class TiendayaCurrencies{


     private Integer id;
     private String title;
     private String code;
     private String symbolLeft;
     private String symbolRight;
     private char decimalPlace;
     ...

includeProperties有什么问题吗?(只有我能想到的地方......)任何人都可以提出建议......我已经尝试了一切......

  

编辑:

public class SocialIconsAction extends ActionSupport {

    private List<TiendayaCurrencies> _currency=new ArrayList<>();
    private String sample="working";

    public String getSample() {
        return sample;
    }

    public void setSample(String sample) {
        this.sample = sample;
    }
    ...


@Action(value = "currencies", results = {
@Result(name = "success", type = "json", params = {"includeProperties", "sample"})})

...

作为json输出,它给了我: {“sample”:“working”} ,这意味着它工作正常。那么为什么它不能使用 ArrayList ??

1 个答案:

答案 0 :(得分:2)

Struts2 JSON插件将序列化您的整个操作,包括带有getter的所有(非瞬态)属性

因为你隐藏了你的变量(绝对不是最佳实践,特别是因为它迫使你手动编写每个getter和setter ... brr),并且你有变量和getter的不同名称,你指的是变量,但你应该指向吸气剂(然后是currency而不是_currency):

@Action(value = "currencies", results = {
    @Result(name = "success", 
            type = "json", 
          params = {"includeProperties","currency\\[\\d+\\]\\..*"})
})

另请注意,您可以将described here技术通常优先选择的根对象指定为TOM

includeProperties