Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

java - Struts2 + Json Serialization of items

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...