I'm getting "org.json.JSONException: No value for name" when running this code to get the JSON. However, when I use: (https://api.myjson.com/bins/j5f6b), a tester JSON URL, it gives me the desired output.

have tried changing it to JSON Object in places but that isn't helping.

public class fetchData extends AsyncTask<Void,Void,Void> {
String data ="";
String dataParsed = "";
String singleParsed ="";
@Override
protected Void doInBackground(Void... voids) {
    try {
        URL url = new URL("http://www.free-map.org.uk/fm/ws/bsvr.php?bbox=-0.73,51.04,-0.71,51.06&way=highway&format=json");
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        while(line != null){
            line = bufferedReader.readLine();
            data = data + line;
        }

        JSONObject jsonObject = new JSONObject(data);
        JSONArray JA = jsonObject.getJSONArray("features");
        for (int i = 0; i < JA.length(); i++) {
            JSONObject JO = (JSONObject) JA.get(i);
            singleParsed =  "name:" + JO.get("name") + "\n";
            dataParsed = dataParsed + singleParsed +"\n" ;

            System.out.print(JO);
        }



    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return null;
}


protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);

    twod.data.setText(this.dataParsed);

}

Expected result: Name output Actual Result: org.json.JSONException: No value for name

1 Answers

0
sanoJ On

The attribute name is inside the properties object. So to access the name first get the properties JSON object and use it.

    JSONArray JA = jsonObject.getJSONArray("features");
    for (int i = 0; i < JA.length(); i++) {
        JSONObject JO = (JSONObject) JA.get(i);
        singleParsed =  "name:" + JO.getJSONObject("properties").get("name") + "\n"; // add .getJSONObject("properties")
        dataParsed = dataParsed + singleParsed +"\n" ;

        System.out.print(JO);
    }