first of all, I've read a ton of similar questions on this site and none has solved my problem so
I have this json file that I create using php :
{
"done":true,
"data":"[
{\"id\":\"5099\",\"user_id\":\"892\"},
{\"id\":\"5100\",\"user_id\":\"892\"}
....
]"}
now in java android I want to parse it but it gives me this error: JSON.TypeMismatch
this is my android code to parse the json file:
//class from which I get the json in a JSONObject - works fine so far
JSONObject httpResult = itemHttpRequest.get("/fetch?currentList=&sort=recent&extra=");
try {
JSONArray httpData = httpResult.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
but it keeps giving me error.
is it because the data array in my json file is surrounded by quotes?
please help
For sure, data
is a String (character surrounded by quotes), it can't be read as a JSONArray.
If you can't make your php to generate a JSON array, what you can do on Android size, is to get the data
string with :
String data = httpResult.getString("data");
then you can create a JSONARRAY with :
JSONArray dataArray = new JSONArray(data)
"data":"[
{\"id\":\"5099\",\"user_id\":\"892\"},
{\"id\":\"5100\",\"user_id\":\"892\"}
....
]"
is a string
But
"data":[
{"id":"5099","user_id":"892"},
{"id":"5100","user_id":"892"}
....
]
is array
You are supplying invalid JSON. You need to correct your JSON by removing extra quotes. You can always use some validator to spot these types of problem Eg
{
"done": true,
"data": [
{
"id": "5099",
"user_id": "892"
},
{
"id": "5100",
"user_id": "892"
}
]
}
Use this to convert JSON array to string
private String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the
* BufferedReader return null which means there's no more data to
* read. Each line will appended to a StringBuilder and returned as
* String.
*/
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Try with this
JsonArray array = new JsonArray(value)
value :- Should have proper jsonarray format. otherwise it will throw a JsonException
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.