0

I'm trying to parse the following JSON string

String _message = "GetXTRONResult: \"[{\"xtron\":\"Acub1\"},{\"xtron\":\"Acub2\"},{\"xtron\":\"Acub3A\"}]\"";

JSONObject jsonObj = new JSONObject(_message);

//Try to convert to array
JSONArray array = jsonObj.getJSONArray("GetXTRONResult");  //FAILS !

What is the best way to parse the above please?

UPDATE: This is what the value is during debugging:

{"GetXTRONResult":"[{\"xtron\":\"Acub1\"},{\"xtron\":\"Acub2\"},{\"xtron\":\"Acub3A\"}]"}

org.json.JSONException: Value .... at GetXTRONResultof type java.lang.String cannot be converted to JSONArray

SOLUTION THAT WORKED FOR ME: I had to use the iterator as follows:

ArrayList list = new ArrayList();
JSONObject jsonObj = new JSONObject(_message);
Iterator<?> keys = jsonObj.keys();
if (keys.hasNext()) {
   JSONArray array = new JSONArray((String) jsonObj.get((String) keys.next()));
for (int i = 0; i < array.length(); ++i) {  
    list.add(array.getJSONObject(i).getString("xtron").toString()); 
}

3 Answers3

0

You have some errors in your json string, like "[.

You can't use quotes that wrap your list.

This one should work:

String _message = "{\"GetXTRONResult\": [{\"xtron\":\"Acub1\"},{\"xtron\":\"Acub2\"},{\"xtron\":\"Acub3A\"}]}";

    JSONObject jsonObj = new JSONObject(_message);

    //Try to convert to array
    JSONArray array = jsonObj.getJSONArray("GetXTRONResult");  

    System.out.println(array);

Output: [{"xtron":"Acub1"},{"xtron":"Acub2"},{"xtron":"Acub3A"}]

Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
0

To avoid your confusion when making JSON in java/android

you could use single quote (') instead of double quote (") for JSON inside Java Code

For example:

from

"{\"xtron\":\"Acub1\"},{\"xtron\":\"Acub2\"},{\"xtron\":\"Acub3A\"}"

to be something like this

"{'xtron':'Acub1'},{'xtron':'Acub2'},{'xtron':'Acub3A'}"
Sruit A.Suk
  • 7,073
  • 7
  • 61
  • 71
0

I think this is what you're looking for:

JSONObject rootObj = new JSONObject(jsonString);
String theArrayJSON = rootObj.getJSONArray("GetXTRONResult");

JSONObject theArray = new JSONObject(theArrayJSON);
Robin Kanters
  • 5,018
  • 2
  • 20
  • 36