how to get key value from json object in java

www.‮tual‬turi.com
how to get key value from json object in java

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.

Created Time:2017-11-01 20:42:55  Author:lautturi