Error when parsing JSON

2

I have a problem parsing a JSON, reusing source code I had:

protected Boolean doInBackground(final String...args) {
    String datos = leeJSon(this.ruta);
    Log.d("1", datos);
    try {
        JSONObject jsonObject = new JSONObject(datos);
        String strData = jsonObject.getString(""); //Puede que haya que quitar esta línea
        JSONArray jsonContent = new JSONArray(strData);
        int numItems = jsonContent.length();
        MainActivity.hacks = new Hack[numItems];
        for (int i = 0; i < numItems; i++) {
            JSONObject itemJson = jsonContent.getJSONObject(i);
            Hack hack = new Hack();
            hack.setTitle(itemJson.getString("Title"));
            hack.setBreachDate(itemJson.getString("BreachDate"));
            hack.setDescription(itemJson.getString("Description"));
            MainActivity.hacks[i] = hack;
        }

    } catch(Exception e) {
        e.printStackTrace();
    }
    return true;
}

private String leeJSon(String url) {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }

        }
    } catch(ClientProtocolException e) {
        e.printStackTrace();
    } catch(IOException e) {
        e.printStackTrace();
    }
    return builder.toString();
}
    
asked by Aris Guimerá 16.06.2016 в 17:25
source

1 answer

1

HttpClient , DefaultHttpClient , httpGet and ClientProtocolException are classes of Apache , you have to change your implementation using HttpUrlConnection

If it is necessary to use the Apache classes temporarily, you have to add within your file build.gradle :

android {
    ...
    ...
    useLibrary 'org.apache.http.legacy'
    ...
}

It is advisable to change to HttpUrlConnection

As for that in this line you have a problem:

 String strData = jsonObject.getString(""); 

It's wrong to have an empty string, you have to define what value to get from the json.

or delete that line and define what the array name is:

// String strData = jsonObject.getString(""); 
  JSONArray jsonContent = new JSONArray("nombre del array");
    
answered by 16.06.2016 в 18:20