import org.json.*; // create a JSONObject with some data String jsonStr = "{\"name\": \"John\", \"age\": 31, \"city\": \"New York\"}"; JSONObject jsonObj = new JSONObject(jsonStr); // retrieve values using the get() method String name = jsonObj.get("name").toString(); // "John" int age = jsonObj.getInt("age"); // 31 String city = jsonObj.getString("city"); // "New York"
import org.json.*; // create a JSONObject with an array String jsonStr = "{\"numbers\":[1,2,3,4,5]}"; JSONObject jsonObj = new JSONObject(jsonStr); // retrieve an array using the get() method and iterate over its values JSONArray numbersArray = jsonObj.getJSONArray("numbers"); for (int i = 0; i < numbersArray.length(); i++) { int number = numbersArray.getInt(i); System.out.println(number); // prints each number in the array }
import org.json.*; // create an empty JSONObject and add values to it JSONObject jsonObj = new JSONObject(); jsonObj.put("name", "Jane"); jsonObj.put("age", 25); jsonObj.put("city", "London"); // retrieve values using the get() method String name = jsonObj.getString("name"); // "Jane" int age = jsonObj.getInt("age"); // 25 String city = jsonObj.optString("place", "unknown"); // "unknown", since the key "place" doesn't exist
org.json json 20211205