String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; JSONObject jsonObj = new JSONObject(jsonString); String[] keys = jsonObj.getNames(); System.out.println(Arrays.toString(keys)); // Output: [name, age, city]
JSONObject obj = new JSONObject(); obj.put("firstName", "John"); obj.put("lastName", "Doe"); String[] keys = obj.getNames(); System.out.println(Arrays.toString(keys)); // Output: [firstName, lastName]In this example, we create a new JSON object and add two key-value pairs to it using the `put()` method. We then use the `getNames()` method to get an array of the keys in the JSON object, which are then printed to the console. In both examples, the `org.json` package/library is used. It is a lightweight and easy-to-use library for working with JSON data in Java.