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()); 
}
4

3 回答 3

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"}]

于 2013-09-14T20:32:13.260 回答
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'}"
于 2013-09-14T20:41:15.690 回答
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);
于 2013-09-14T20:56:40.437 回答