A Solution to Hierarcy Cycle Problem with JSON: JSON Filter

6 06 2008

When you have a cycle in your domain model, beacuse sometimes you realy need it*, then with Spring JsonView, indeed you may have same problem in different cases, while converting Java objects to JSON objects, you can get en error :

net.sf.json.JSONException: There is a cycle in the hierarchy!

with a following unusefull stack trace:)

First of all, think carefully fi you really do need this cycle in the dependency. If you don’t, remove it.
If you do, the you can use, JSON filters.

I will give an example code to show it. In the code, resulting JSON object will contain only id, name and description fields and values of the objects.

     JsonConfig config = new JsonConfig();
     config.setJsonPropertyFilter(new PropertyFilter() {
        public boolean apply(Object source, String name, Object value) {
              if ("name".equals(name) || "description".equals(name) || "id".equals(name)) {
                  return false;
              }
              return true;
           }
       });
       List jsonObjects = new ArrayList();
       for (Object object : objects) {
           jsonObjects.add(JSONSerializer.toJSON(object, config));
       }
     //Here you have jsonObjects, do whatever you need.
      ...

This is a sample code. It depends on you how to use this in a proper way! :)

* Consider, you have an class X with composition Y, and in Y class, if you need all Xs referenced by Y, then you will probably have a property containing list of X. Then you have cycle! For example, Employee works on a Department, so Employee has a composition with Department, in Department you need all employees workin in this department.








Follow

Get every new post delivered to your Inbox.