mikeb
mikeb

Reputation: 727

org.json.JSONException: JSONArray[0] is not a JSONObject

Output of String jsreturn: [{"type":1, "msg":"ERROR"}].

I'm trying to get the content of msg key which is ERROR. I'm doing that by transforming string return into an array. However I'm getting some errors commented next to each line on the follow code. Any insight?

 Vector<ClsReturn> ret = null;
 ret = ds.id(collection, "fs",in_uri );

 String jsReturn = ret.toString();

 JSONObject myJsonObject = new JSONObject(ret);

 JSONArray array = new JSONArray(jsReturn); 

 int i = 0;

 while(i < array.length()){
     myJsonObject = array.getJSONObject(i); //org.json.JSONException: JSONArray[0] is not a JSONObject.
     System.out.println(myJsonObject.getString("msg"));
     i++;
 }

Upvotes: 1

Views: 15125

Answers (1)

MrElephant
MrElephant

Reputation: 312

I dont know if I have understood your question, I think it is easy, this works:

    String jsReturn =" [{\"type\":1, \"txt\":\"ERROR\"}]";
    JSONArray array = new JSONArray(jsReturn); 
    int i = 0;
    JSONObject myJsonObject = new JSONObject();
    while(i < array.length()){
        myJsonObject = array.getJSONObject(i); 
        System.out.println(myJsonObject.getString("txt"));
        i++;
    }

Upvotes: 3

Related Questions