Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 989
danny.lesnik Avatar asked Jan 20 '23 16:01

danny.lesnik


1 Answers

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.

like image 52
Quaternion Avatar answered Jan 26 '23 10:01

Quaternion