JSON Serialization in Liferay

Many times we have requirement to convert Liferay service response or any list into JSON object. Most of the time we are doing this manually.

There are other ways as well by which we can convert List into JSON string.
Service builder has support for JSON  serialization,too. The json-enabled attribute of entity tag specifies whether or not the entity should be annotated for JSONserialization.
By default, if the remote-service value is true, then thejson-enabled value is true.
Column tag has the same attribute, json-enabled.
It specifies whether or not the column should be annotated for JSON serialization. By default, if the json-enabled value in the entity element is true, then the json-enabled value in the column element is true.

json enabled is true for enttity TestJson so all the column tags will have by default json-enabled as true.
In case if you want to exclude any property to not to appear when you serialize then you can set json-enabled as false. For email column json-enabled is set to false.

build-service and check TestJSONModelImpl class. For the field json-enabled is true you will see @JSON annotation. For excluded fields you will see @JSON(include = false) .

Now you can easily convert your list returned using Liferay services into JSON format.

JSONSerializer jsonSerializer = JSONFactoryUtil.createJSONSerializer();
String json = jsonSerializer.serialize(list);

You can also exclude fields you don't need in JSON.

Same way you can use serialize OOB data as well like user.

 List<User> userList = UserLocalServiceUtil.getUsers(-1, -1);
 String json = JSONFactoryUtil.looseSerialize(userList);

 By default collections are excluded from serialization . You can include them using below way.
 String json  = JSONFactoryUtil.looseSerialize(userList,"organizations")

Next PostNewer Post Previous PostOlder Post Home


  1. How do you format dates here? is there a way to format that?

  2. Thanks!!! i was in trouble but with this post about the json-enable in service.xml i solve the trouble and the JSONFactoryUtil.looseSerialize works fine! Thank you again, regards from Colombia.