Sunday, 11 September 2016

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.

JSONArray jsonArr = JSONFactoryUtil.createJSONArray();
for (User user : userList)
{
JSONObject json = JSONFactoryUtil.createJSONObject();
json.put("name", user.getFullName());
json.put("id", user.getUserId());
jsonArr.put(json);
}
return jsonArr.toString();



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.


<entity name="TestJSON" table="json_test" local-service="true" remote-service="false" json-enabled="true">
<!-- PK fields -->
<column name="keyId" type="long" primary="true" />
<!-- Audit fields -->
<column name="companyId" type="long" />
<column name="groupId" type="long" />
<!-- Other fields -->
<column name="firstName" type="String" json-enabled="true" />
<column name="lastName" type="String" json-enabled="true"/>
<column name="email" type="String" json-enabled="false"/>
<!-- Finder methods -->
</entity>

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.



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

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



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")

 Covert List to JSONArray:-

Might be you won't be aware that you can't use existing portal *JsonSerializer.java class in Liferay plugin portlets. So if you want to get JsonArray response of existing liferay service then you can use below code :


import net.sf.json.JSONArray;

List myList = UserLocalserviceUtil.getUsers();
JSONArray jsonArray = JSONArray.fromObject(MyList);