Values Cannot be Converted to JSON Array

Hawke

New Member
#1
This is the function that's giving me the problem:
Mã:
    public String URLToJson() {
    String result = "";
    String jsonString = ReadingURL(" here goes my URL that reads a JSON ");
    JSONObject jsonResult = null;
    try {
        jsonResult = new JSONObject(jsonString);
        JSONArray data = jsonResult.getJSONArray("Configuracion");
        if (data != null) {
            for (int i = 0; i <= data.length(); i++) {
                result =  result + "Dirección: " + data.getJSONObject(i).getString("Direccion") + "\n";
                result =  result + "Cédula: " + data.getJSONObject(i).getString("Cedula") + "\n";
                result =  result + "Nombre: : " + data.getJSONObject(i).getString("Nombre") + "\n";
                result =  result + "Teléfono : " + data.getJSONObject(i).getString("Telefono") + "\n";
                result =  result + "Hacienda: " + data.getJSONObject(i).getString("Hacienda") + "\n";
            }
        }
        return result;
    }catch (JSONException e){
        e.printStackTrace();
        return "Error Reading JSON Data";
    }
}
And then this comes up:
Mã:
`W/System.err: org.json.JSONException: Value {"Direccion":"Somewhere","Cedula":"111111","Nombre":"Something","Telefono":"2222-2440","Hacienda":"Something"} at Configuracion of type org.json.JSONObject cannot be converted to JSONArray
        at org.json.JSON.typeMismatch(JSON.java:100)
W/System.err:     at org.json.JSONObject.getJSONArray(JSONObject.java:588)
        at com.example.user.mypos.PrintManager.URLToJson(PrintManager.java:977)
W/System.err:     at com.example.user.mypos.PrintManager$4.run(PrintManager.java:917)
        at java.lang.Thread.run(Thread.java:818)W/System.err: org.json.JSONException: Value { the values that are supposed to be }  of type org.json.JSONObject cannot be converted to JSONArray`
ReadingURL basically reads the content of an URL, that has the JSON in String.
 

Admin

Administrator
Thành viên BQT
#2
From the exception it's clear that the JSON string returned by the URL is of type JSONObject not of JSONArray .
Value { the values that are supposed to be } of type org.json.JSONObject cannot be converted to JSONArray
JSON object will starts with { & ends with }
{ "KEY1":"VALUE1", "KEY2":"VALUE2" }
and JSON array will starts with [ and ends with ] .
Mã:
[
{"KEY1":"VALUE1","KEY2":"VALUE2"},{"KEY1":"VALUE1","KEY2":"VALUE2"}
]
So you are getting this exception because you are trying to convert JSON object to JSON array.
 
Top