To get the value of a key in a JSON object in Java, you can use the get()
method of the JSONObject
class. This method takes a string as an argument and returns the value associated with the key, or null
if the key is not found.
Here's an example of how you can get the value of a key in a JSON object in Java:
import org.json.JSONObject; // ... String jsonString = "{ \"name\": \"John\", \"age\": 30, \"city\": \"New York\" }"; JSONObject json = new JSONObject(jsonString); String name = json.getString("name"); int age = json.getInt("age"); String city = json.getString("city");
In this example, the json
object represents a JSON object containing three key-value pairs. The name
, age
, and city
variables hold the values associated with the respective keys.
The get()
method can also take a default value as an argument, which will be returned if the key is not found. This can be useful if you want to handle the case where the key is not present in the JSON object.