Struts2 + Json 项目序列化

发布于 2024-10-14 12:43:26 字数 1052 浏览 3 评论 0原文

我有以下课程:

public class Student {
    private Long id  ;
    private String firstName;
    private String lastName;
private Set<Enrollment> enroll = new HashSet<Enrollment>();
//Setters and getters
}

public class Enrollment {
    private Student student;
    private Course course;
    Long enrollId;

//Setters and Getters
}

我有 Struts2 控制器,我想仅返回 Student 类的序列化实例。

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

private Student student;

@Autowired
DbService dbService;

public String populate(){
    return "populate";
}

@Action(value="/getJson", results = {
        @Result(name="success", type="json")})
public String test(){
    student =  dbService.getSudent(new Long(1));
    return "success";
}

@JSON(name="student")
public Student getStudent() {
    return student;
}
public void setStudent(Student student) {
    this.student = student;
}

}

它返回带有所有子类的可序列化学生对象,但我只想返回没有哈希集的学生对象。 我如何告诉 Struts 仅序列化对象? 我确实启用了延迟加载,并且哈希集作为代理类返回。

I have the following classes:

public class Student {
    private Long id  ;
    private String firstName;
    private String lastName;
private Set<Enrollment> enroll = new HashSet<Enrollment>();
//Setters and getters
}

public class Enrollment {
    private Student student;
    private Course course;
    Long enrollId;

//Setters and Getters
}

I have Struts2 controller and I would like to to return Serialized instance of Class Student only.

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

private Student student;

@Autowired
DbService dbService;

public String populate(){
    return "populate";
}

@Action(value="/getJson", results = {
        @Result(name="success", type="json")})
public String test(){
    student =  dbService.getSudent(new Long(1));
    return "success";
}

@JSON(name="student")
public Student getStudent() {
    return student;
}
public void setStudent(Student student) {
    this.student = student;
}

}

It returns me the serializable student object with all sub classes, but I would like to have only student object without the hashset returned .
How can I tell Struts to serialize only the object?
I do have Lazy loading enabled and hashset is returned as proxy class.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陈甜 2024-10-21 12:43:26

请参阅此处的答案,其中显示了包含和排除属性的用法。我不认为该示例清楚地显示了排除嵌套对象,但我已将其用于此目的。如果您仍然遇到问题,我将发布一个正则表达式来证明这一点。

Struts 2 中的 Json 插件出现问题

编辑:
以下是在注释中使用排除属性的示例,该注释阻止嵌套成员的序列化:

@ParentPackage("json-default")
@Result(type = "json", params = {
        "excludeProperties",
        "^inventoryHistory\\[\\d+\\]\\.intrnmst, selectedTransactionNames, transactionNames"
    })
public class InventoryHistoryAction extends ActionSupport {
...

inventoryHistory 的类型为 InventoryHistory ,是一个 JPA 实体对象, intrnmst 引用另一个表,但由于延迟加载,如果它被序列化,则会在以下情况下导致异常:操作是 JSON 序列化的,因此添加了排除参数来防止这种情况发生。

请注意,

\\ 

每个 \ 字符都是必需的,因此仅在需要两个 \ 的 xml 中使用单个 \,因为要对字符串进行转义才能正确解析。

See the answer here which shows the use of include and exclude properties. I don't think the example clearly shows excluding nested objects however I have used it for this purpose. If you still have issues I'll post a regex which will demonstrate this.

Problem with Json plugin in Struts 2

Edit:
Here is an example of using exclude properties in an annotation which blocks the serialization of a nested member:

@ParentPackage("json-default")
@Result(type = "json", params = {
        "excludeProperties",
        "^inventoryHistory\\[\\d+\\]\\.intrnmst, selectedTransactionNames, transactionNames"
    })
public class InventoryHistoryAction extends ActionSupport {
...

inventoryHistory is of type InventoryHistory a JPA entity object, intrnmst references another table but because of lazy loading if it were serialized it would cause an Exception when the action is JSON serialized for this reason the exclude parameter has been added to prevent this.

Note that

\\ 

is required for each \ character, so a single \ would only be used in the xml where two are required because of escaping for the string to be parsed right.

北方的韩爷 2024-10-21 12:43:26
    @Controller
    @Results({  
        @Result(name="json",type="json"
                , params={"root","outDataMap","excludeNullProperties","true"
                        ,"excludeProperties","^ret\\[\\d+\\]\\.city\\.province,^ret\\[\\d+\\]\\.enterprise\\.userinfos","enableGZIP","true"
                })
    })
    public class UserinfoAction extends BaseAction {
                @Action(value="login")

        public String login(){
            if(jsonQueryParam!=null && jsonQueryParam.length()>0)
            {
                user = JsonMapper.fromJson(jsonQueryParam, TUserinfo.class);
            }
            Assert.notNull(user);
             //RESULT="ret" addOutJsonData: put List<TUserinfo> into outDataMap with key RESULT for struts2 JSONResult  
            addOutJsonData(RESULT, service.login(user));
            return JSON;
        }



public class TUserinfo implements java.io.Serializable {
    private static final long serialVersionUID = 1L;
    private String userid;
    private String username;
    private String userpwd;
    private TEnterpriseinfo enterprise;
    private String telphone;
    private TCity city;
......
}

public class TEnterpriseinfo implements java.io.Serializable {
    private String enterpriseid;
    private String enterprisename;
    private Set<TUserinfo> userinfos = new HashSet<TUserinfo>(0);
.......}

设置extractProperties属性前,结果如下:

    {"ret":[
    {
    "city":{"cityename":"tianjin","cityid":"12","cityname":"天津"
           ,"province": {"provinceename":"tianjing","provinceid":"02","provincename":"天津"}
      }
    ,"createddate":"2014-01-07T11:13:58"
    ,"enterprise":{"createddate":"2014-01-07T08:38:00","enterpriseid":"402880a5436a227501436a2277140000","enterprisename":"测试企业2","enterprisestate":0
              ,"userinfos":[null,{"city":{"cityename":"beijing","cityid":"11","cityname":"北京","province":{"provinceename":"beijing","provinceid":"01","provincename":"北京市"}
    },"comments":"ceshi","createddate":"2004-05-07T21:23:44","enterprise":null,"lastlogindate":"2014-01-08T08:50:34","logincount":11,"telphone":"2","userid":"402880a5436a215101436a2156e10000","username":"0.5833032879881197","userpwd":"12","userstate":1,"usertype":0}]
      }
,"lastlogindate":"2014-01-08T10:32:43","logincount":0,"telphone":"2","userid":"402880a5436ab13701436ab1b74a0000","username":"testUser","userpwd":"333","userstate":1,"usertype":0}]
    }

设置extractProperties属性后,不存在province和userinfos节点,结果如下:

{"ret":
    [{
    "city":{"cityename":"tianjin","cityid":"12","cityname":"天津"}
    ,"createddate":"2014-01-07T11:13:58"
    ,"enterprise":{"createddate":"2014-01-07T08:38:00","enterpriseid":"402880a5436a227501436a2277140000","enterprisename":"测试企业2","enterprisestate":0}
    ,"lastlogindate":"2014-01-08T11:05:32","logincount":0,"telphone":"2","userid":"402880a5436ab13701436ab1b74a0000","username":"testUser","userpwd":"333","userstate":1,"usertype":0
    }]
}
    @Controller
    @Results({  
        @Result(name="json",type="json"
                , params={"root","outDataMap","excludeNullProperties","true"
                        ,"excludeProperties","^ret\\[\\d+\\]\\.city\\.province,^ret\\[\\d+\\]\\.enterprise\\.userinfos","enableGZIP","true"
                })
    })
    public class UserinfoAction extends BaseAction {
                @Action(value="login")

        public String login(){
            if(jsonQueryParam!=null && jsonQueryParam.length()>0)
            {
                user = JsonMapper.fromJson(jsonQueryParam, TUserinfo.class);
            }
            Assert.notNull(user);
             //RESULT="ret" addOutJsonData: put List<TUserinfo> into outDataMap with key RESULT for struts2 JSONResult  
            addOutJsonData(RESULT, service.login(user));
            return JSON;
        }



public class TUserinfo implements java.io.Serializable {
    private static final long serialVersionUID = 1L;
    private String userid;
    private String username;
    private String userpwd;
    private TEnterpriseinfo enterprise;
    private String telphone;
    private TCity city;
......
}

public class TEnterpriseinfo implements java.io.Serializable {
    private String enterpriseid;
    private String enterprisename;
    private Set<TUserinfo> userinfos = new HashSet<TUserinfo>(0);
.......}

before set the excludeProperties property,the result is below:

    {"ret":[
    {
    "city":{"cityename":"tianjin","cityid":"12","cityname":"天津"
           ,"province": {"provinceename":"tianjing","provinceid":"02","provincename":"天津"}
      }
    ,"createddate":"2014-01-07T11:13:58"
    ,"enterprise":{"createddate":"2014-01-07T08:38:00","enterpriseid":"402880a5436a227501436a2277140000","enterprisename":"测试企业2","enterprisestate":0
              ,"userinfos":[null,{"city":{"cityename":"beijing","cityid":"11","cityname":"北京","province":{"provinceename":"beijing","provinceid":"01","provincename":"北京市"}
    },"comments":"ceshi","createddate":"2004-05-07T21:23:44","enterprise":null,"lastlogindate":"2014-01-08T08:50:34","logincount":11,"telphone":"2","userid":"402880a5436a215101436a2156e10000","username":"0.5833032879881197","userpwd":"12","userstate":1,"usertype":0}]
      }
,"lastlogindate":"2014-01-08T10:32:43","logincount":0,"telphone":"2","userid":"402880a5436ab13701436ab1b74a0000","username":"testUser","userpwd":"333","userstate":1,"usertype":0}]
    }

after set the excludeProperties property,there are not exist province and userinfos nodes, the result is below:

{"ret":
    [{
    "city":{"cityename":"tianjin","cityid":"12","cityname":"天津"}
    ,"createddate":"2014-01-07T11:13:58"
    ,"enterprise":{"createddate":"2014-01-07T08:38:00","enterpriseid":"402880a5436a227501436a2277140000","enterprisename":"测试企业2","enterprisestate":0}
    ,"lastlogindate":"2014-01-08T11:05:32","logincount":0,"telphone":"2","userid":"402880a5436ab13701436ab1b74a0000","username":"testUser","userpwd":"333","userstate":1,"usertype":0
    }]
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文