import org.json.JSONObject;
public class JsonExample {
public static void main(String[] args) {
// 创建一个 JSONObject 对象
JSONObject jsonObject = new JSONObject();
// 向 JSONObject 中添加键值对
jsonObject.put("name", "Alice");
jsonObject.put("age", 25);
jsonObject.put("isStudent", false);
// 创建一个嵌套的 JSONObject
JSONObject address = new JSONObject();
address.put("city", "Beijing");
address.put("country", "China");
// 将嵌套的 JSONObject 添加到主 JSONObject 中
jsonObject.put("address", address);
// 输出 JSON 字符串
System.out.println(jsonObject.toString());
// 从 JSONObject 中获取数据
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
boolean isStudent = jsonObject.getBoolean("isStudent");
// 获取嵌套的 JSONObject 并从中提取数据
JSONObject addr = jsonObject.getJSONObject("address");
String city = addr.getString("city");
String country = addr.getString("country");
// 输出提取的数据
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Is Student: " + isStudent);
System.out.println("City: " + city);
System.out.println("Country: " + country);
}
}
import org.json.JSONObject; 导入了 org.json 包中的 JSONObject 类。new JSONObject() 创建了一个空的 JSON 对象。put() 方法向 JSON 对象中添加键值对,支持多种数据类型(如字符串、整数、布尔值等)。JSONObject 并将其作为值添加到主 JSON 对象中,形成嵌套结构。toString() 方法将 JSON 对象转换为字符串并打印出来。getXXX() 方法(如 getString()、getInt() 等)从 JSON 对象中提取相应的值。上一篇:java service
下一篇:java reduce
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站