liferayliferay-6

create JSONObject and JSONArray in Liferay Portlet


Which is the best option to create a JSONObject and JSONArray in Liferay portlet?

You can't do Java simple way:

JSONObject json = new JSONObject();
JSONArray arrayJson = new JSONArray();

Error:

Cannot instantiate the type JSONObject

Cannot instantiate the type JSONArray


Tried with JSONFactoryUtil and it works but its deprecated.

com.liferay.util.json.JSONFactoryUtil

JSONObject json = JSONFactoryUtil.createJSONObject();
JSONArray arrayJson = JSONFactoryUtil.createJSONArray();

Solution

  • JSONFactoryUtil.createJSONObject() and JSONFactoryUtil.createJSONArray() are not deprecated, neither in Liferay 6.x nor in Liferay 7.x.

    If you still want to use new JSONObject() and new JSONArray(), you can import org.json.

    Maven:

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20190722</version>
    </dependency>
    

    Gradle:

    compileOnly group: 'org.json', name: 'json', version: '20190722'
    

    Try a different version if this version doesn‘t work for you.