John Staples
John Staples

Reputation: 11

Parsing and retrieving elements in a JSON Java

   JSONParser parser = new JSONParser();
   try {
       Object obj = parser.parse(new FileReader("C:/Users/dan/Documents/rental.txt"));
       JSONObject jsonObject = (JSONObject) obj;
       for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
           String key = (String) iterator.next();
           System.out.println(jsonObject.get(key));
       }

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

Following is the JSON String:

{
    "Search": {
        "VehicleList": [
            {
                "sipp": "CDMR",
                "name": "Ford Focus",
                "price": 157.85,
                "supplier": "Hertz",
                "rating": 8.9
            },
            {
                "sipp": "FVAR",
                "name": "Ford Galaxy",
                "price": 706.89,
                "supplier": "Hertz",
                "rating": 8.9
            }
          ]
        }
      }
 }

Hi, I can iterate over the whole JSON object with my code but right now I want to print out the name of a vehicle and the price of the vehicle individually. Any help would be appreciated, I am a beginner when it comes to working with JSON.

Upvotes: 0

Views: 45

Answers (2)

Murat Karagöz
Murat Karagöz

Reputation: 37584

Your JSON is structured like this JsonObject -> JsonArray-> [JsonObject]
With that in mind you can access the name and price with this

Object obj = parser.parse(new FileReader("C:/Users/dan/Documents/rental.txt"));
JSONArray jsonArray = (JSONObject) obj.getJsonArray("VehicleList");
for(JSONObject jsonObject : jsonArray){
        System.out.println(jsonObject.getString("name") + " " + jsonObject.getDouble("price"))
    }
}

Depending on your import library it may deviate from the above but the concept is the same.

Upvotes: 1

Sheetal Mohan Sharma
Sheetal Mohan Sharma

Reputation: 2924

You need to iterate over the json. For example.

$.Search.VehicleList[0].price will give you [157.85]
$.Search.VehicleList[1].price will give you [706.89]

http://www.jsonquerytool.com/ will come handy for you :)

Upvotes: 0

Related Questions