简体   繁体   中英

Issue in parsing Json using JsonObject

I am facing issue while parsing the JsonResponse . Getting error

org.json.JSONException: A JSONArray text must start with '[' at character 1

Actual API Response

["fa0d30bf-49ad-47be-a840-34393493hdkjfd"]

I need to extract the value out of this array. Below is the code that I've tried.

Gson gson = new Gson();
String jsonString = "["fa0d30bf-49ad-47be-a840-34393493hdkjfd"]"
String gsonString = gson.toJson(jsonString);
JSONArray arr = new JSONArray(gsonString);
String api = arr.getJSONObject(indexOfArray).toString(); // indexOfArray = 0

Could someone help me here.

If you are using Gson, you can try below code

String jsonString = "[\"fa0d30bf-49ad-47be-a840-34393493hdkjfd\"]";

Gson gson = new Gson();
JsonArray arr = gson.fromJson (jsonString, JsonElement.class).getAsJsonArray(); //Converts the response string to JsonArray

String api = arr.get(indexOfArray).getAsString(); // indexOfArray = 0

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