Parsing JSON Object in Java
To parse a JSON object in Java, you can use the org.json library.
To parse a JSON object in Java, you can use the org.json library. This library provides a simple and easy-to-use set of classes to parse and generate JSON in Java.
Here is an example of how you can use the org.json library to parse a JSON object in Java:
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
// Create a JSON object from a string
String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
JSONObject obj = new JSONObject(jsonString);
// Get values from the object
String name = obj.getString("name");
int age = obj.getInt("age");
String city = obj.getString("city");
// Print the values
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
}
}This code creates a JSON object from a string and uses the getString() and getInt() methods to retrieve the corresponding values. Note that org.json is not part of the standard Java SDK, so you must add it to your project dependencies. For Maven, include the following in your pom.xml:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20231013</version>
</dependency>Once the dependency is configured, the example will compile and run successfully. For production environments, wrap the parsing logic in a try-catch block to handle JSONException when the input string is malformed.