Converting JSON to Java Objects
The org.json
library provides convenient methods for converting JSON data to Java objects. For example, you can use the get
methods of JSONObject
to get the values of specific keys as Java objects. Here's an example:
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
JSONObject jo = new JSONObject();
jo.put("name", "John");
jo.put("age", 25);
String name = jo.getString("name");
int age = jo.getInt("age");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
To run the code, execute the following command in your terminal.
javac Main.java && java Main
The above code will create a JSONObject
with two key-value pairs, get the values of the keys "name"
and "age"
, and then print them to the console.