1

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();
Community
  • 1
  • 1
x3k
  • 144
  • 15

1 Answers1

5

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.

mirrom
  • 140
  • 1
  • 9
  • 1
    Thanks! i was using `com.liferay.util.json.JSONFactoryUtil` package, its deprecated but replaced with `com.liferay.portal.kernel.json.JSONFactoryUtil`. [Source: com.liferay.util.json.JSONFactoryUtil](https://docs.liferay.com/portal/6.2/javadocs/com/liferay/util/json/JSONFactoryUtil.html). I realized thanks to your answer. – x3k Jan 27 '20 at 11:27