简体   繁体   中英

Passing a org.json.simpleJSONArray to an Intent in Android as an Extra

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 .

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM