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.

Here is an example of how you can use the org.json library to parse a JSON string:

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:

Name: John
Age: 30
City: New York

You can also use the org.json library to parse a JSON file. Here is an example of how you can do this:

import java.io.FileReader;
import org.json.JSONObject;
import org.json.JSONTokener;

// Parse the JSON file
FileReader reader = new FileReader("data.json");
JSONObject obj = new JSONObject(new JSONTokener(reader));

// 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 parse the JSON file data.json and extract the values for the keys "name", "age", and "city".

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