Appearance
How to parse JSON in Java
To parse a JSON string in Java, you can use the org.json library. This library provides a simple and easy-to-use interface for parsing and manipulating JSON data in Java.
First, add the org.json dependency to your project. For Maven:
xml
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20231013</version>
</dependency>For Gradle:
groovy
implementation 'org.json:json:20231013'java
import org.json.JSONObject;
// Parse the JSON string
String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
JSONObject obj = new JSONObject(jsonString);
// Get the value for the key "name"
String name = obj.getString("name");
// Get the value for the key "age"
int age = obj.getInt("age");
// Get the value for the key "city"
String city = obj.getString("city");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);This will output the following:
java
Name: John
Age: 30
City: New YorkYou can also use the org.json library to parse a JSON file. Here is an example of how you can do this:
java
import java.io.FileReader;
import java.io.IOException;
import org.json.JSONObject;
import org.json.JSONTokener;
public class Main {
public static void main(String[] args) {
try (FileReader reader = new FileReader("data.json")) {
JSONObject obj = new JSONObject(new JSONTokener(reader));
String name = obj.getString("name");
int age = obj.getInt("age");
String city = obj.getString("city");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
} catch (IOException | org.json.JSONException e) {
e.printStackTrace();
}
}
}This will parse the JSON file data.json and extract the values for the keys "name", "age", and "city".
To prevent runtime exceptions when a key is missing or the data type doesn't match, use optString() and optInt() instead of getString() and getInt(). These methods return null or a default value rather than throwing an exception.
There are many other functions and methods available in the org.json library that you can use to manipulate JSON data in Java. For more information, you can refer to the official documentation: https://javadoc.io/doc/org.json/json/latest/index.html