Sander bakker
Sander bakker

Reputation: 505

Get JSON item from URL in Java

I have this link: JSON file

This is stored on a online server. All fine but I want to get an item like "hood_id" or "damage_or_theft_car_id" but somehow my code crashes when I launch it. With an error Json object not found

This is what I tried:

public class JSONParser {
    private String read(BufferedReader bufferedReader) throws IOException {
        //Creates new StringBuilder to avoid escaping chars
        StringBuilder stringBuilder = new StringBuilder();
        //Gets the currentLine
        String currentLine;
        while((currentLine = bufferedReader.readLine()) !=null ){
            //Adds the currentLine to the stringBuild if the currentLine is not null
            stringBuilder.append(currentLine);
        }
        //Returns the StringBuilder is String format
        return stringBuilder.toString();
    }

public JSONObject readJsonFromUrl(String JSONurl) throws IOException, JSONException {
    InputStream url = new URL(JSONurl).openStream();
    try {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url));
        String jsonText = read(bufferedReader);
        JSONArray jsonArray = new JSONArray("[" +jsonText + "]");
        //JSONObject json = new JSONObject(jsonText);
        JSONObject json = jsonArray.getJSONObject(0);
        return json;
    } finally {
        url.close();
    }
}

public void printJSON() throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("http://test.dontstealmywag.ga/api/damage_or_theft_car.php");
    System.out.println(json.toString());
    System.out.println(json.get("hood_id"));
}

}

When I enter json.get("damage_or_theft_car"); The code works. Can anybody help me out? I think the issue is in JSONArrays and JSONOjects

Upvotes: 0

Views: 79

Answers (1)

Gal Dreiman
Gal Dreiman

Reputation: 4009

"hood_id" is not in the top hierarchy of the json, this is why you probably get :

org.json.JSONException: JSONObject["hood_id"] not found

at the line: System.out.println(json.get("hood_id"));

Just to be sure: when you run:

System.out.println(json.get("damage_or_theft_car"));

The program will execute the line and print the json content.


If you do want to print the value of hood_id, you need to dig into each json in the list. For example:

System.out.println(json.getJSONArray("damage_or_theft_car")
                          .getJSONObject(0).get("hood_id"));

Upvotes: 1

Related Questions