org.json library, already available with Cordova.
Include the required components
We need to include the following components in the class, then we will be able to create json arrays and objects (if you use try and catch block , you need to include the JSONException).
import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;
Creating a JSON Object in Java
A JSONObject constructor can be used to convert an external form JSON text into an internal form whose values can be retrieved with the get and opt methods, or to convert values into a JSON text using the
toString methods. A get method returns a value if one can be found, and throws an exception if one cannot be found. An opt method returns a default value instead of throwing an exception, and so is useful for obtaining optional values.
JSONObject and we will use the
put function to add a key.
Creating a JSON Array in Java
String response = "myinformation"; PluginResult result = new PluginResult(PluginResult.Status.OK, response); result.setKeepCallback(true); callbackContext.sendPluginResult(result); // or callbackContext.success(response);
In this case if you try to replace response with one of the previous created variables (item or jsonArray) you will obviously get an error. why ? Because you're sending a not string variable, remember that JSON is a string, we will simply use the toString method of the variables to convert it to JSON String notation :
JSONArray jsonArray = new JSONArray(); JSONObject item = new JSONObject(); // Send an object callbackContext.success(item.toString()); //or Send an array callbackContext.success(jsonArray.toString());
Have fun !