0

I have a problem where I receive JSONArray(from the org.json.simple.JSONArray library) from an API call and I have to pass this JSONArray to a new page/intent while trying to transfer the information in my Android App.

The receive information from the API call, I get a JSONArray, which I now convert to a string and pass it to the new Intent as an string extra.

On the other side, when I receive the string extra, I am not able to convert it back to a JSONArray. Calling new JSONArray(receivedString) causes the following error:

JSONArray cannot be applied to java.lang.String

Anyways, I saw this: How to convert String to JSONObject in Java but it did not help me because the API forces me to use the json.simple library:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

Therefore, I can't convert my simple json to a regular JSONArray (from org.json.JSONArray since org.json.* clashes with org.json.simple).

For example, if I use

org.json.JSONArray
org.json.JSONObect

Instead of the simple library, I get an error:

java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.JSONArray

However, if you don't need to use 'simple' here was the solution that worked found in the link above:

JSONObject jsonObj = new JSONObject("String");

So I can't use org.json and I need to find out a way to convert a string that contains JSONArray format to a JSONObject so I can parse it with the use of org.json.simple library.

Community
  • 1
  • 1
jameswoo
  • 386
  • 3
  • 12

1 Answers1

-1

If you have to use org.json.simple.*, here is the solution to convert java Strings that look like JSONArrays into parseable JSONObjects

String searchResponseJSON = API.search(term, location);

JSONParser parser = new JSONParser();
JSONObject response = null;
try {
    response = (JSONObject) parser.parse(searchResponseJSON);
} catch (ParseException pe) {
    System.out.println("Error: could not parse JSON response:");
    System.out.println(searchResponseJSON);
    System.exit(1);
}");

I hope this helps anyone out there trying to convert strings into parseable JSONObjects with the use of the org.json.simple library!

SaiyanGirl
  • 16,376
  • 11
  • 41
  • 57
jameswoo
  • 386
  • 3
  • 12
  • Your question states that you're trying to parse a String that contains a JSON array, yet you're receiving a `JSONObject` in your answer. – Sotirios Delimanolis May 21 '15 at 19:15
  • No, I stated that I received a string, that looks like a JSON Array, could you point to me where I made an error? – jameswoo May 21 '15 at 20:11
  • Your question discusses passing a String containing the value of a json array around in an `Intent`. Your answer does not address json arrays at all. – Sotirios Delimanolis May 21 '15 at 20:52