danny.lesnik
danny.lesnik

Reputation: 18639

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.

Upvotes: 4

Views: 6529

Answers (2)

uvwxyz888
uvwxyz888

Reputation: 919

    @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
    }]
}

Upvotes: 2

Quaternion
Quaternion

Reputation: 10458

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.

Upvotes: 7

Related Questions