0
   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.

2
  • Actually what you want to do ? Commented Nov 15, 2016 at 12:23
  • I want to print out the name of each vehicle and the price of each vehicle @PSM Commented Nov 15, 2016 at 12:25

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, my import library is the org.json.simple; library
0

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.