Reputation: 2574
I am getting json
Exception while trying to parse a string to jsonArray. I am using loopj
method for json
Parsing. This is the error :
java.lang.String cannot be converted to JSONArray
And this is the json I am trying to parse :
[{\"displayName\":\"Thiruvananthapuram\",\"desc\":\"Partly cloudy\",\"cloudCover\":\"5\",\"dateTime\":\"Sunday October 02\",\"humidity\":\"85\",\"visibility\":\"10\",\"tempCelcius\":\"29\",\"iconClass\":\"PartlyCloudy-s\"}]
My code is
AsyncHttpClient client = new AsyncHttpClient();
client.get("url", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
String jsonStr = new String(responseBody, "UTF-8");
Log.e("Tag ", "on Result " + jsonStr);
JSONArray jsonarray = new JSONArray(jsonStr);
Log.e("Tag ", "jsonArr length " + jsonarray.length());
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
})
Upvotes: 1
Views: 3829
Reputation: 136
you have to replace the "\" to "" then convert into the JsonArray:-
example:-
String jsonStr = new String(responseBody, "UTF-8");
jsonStr = jsonStr.replace("\","");
// now convert it into JsonArray
JSONArray jsonarray = new JSONArray(jsonStr);
hope this help you...
Upvotes: 0
Reputation: 2011
First you have to get jsonObject using jsonString using line below
JSONObject jsnobject = new JSONObject(jsonStr);
Then you can iterate through the jsonObject to get jsonArray object.
JSONArray jsonArray = jsnobject.getJSONArray("your json array key");
Upvotes: 1