org.json.JSONObject Maven 依赖及使用示例

Maven 依赖

在 Maven 项目中,你需要添加以下依赖来使用 org.json.JSONObject

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20231013</version>
</dependency>

最新版本可以在 https://mvnrepository.com/artifact/org.json/json 上查找。

使用示例

1. 创建 JSONObject

import org.json.JSONObject;

public class JsonExample {
    public static void main(String[] args) {
        // 创建一个空的 JSONObject
        JSONObject jsonObject = new JSONObject();
        
        // 添加键值对
        jsonObject.put("name", "John Doe");
        jsonObject.put("age", 30);
        jsonObject.put("isStudent", false);
        
        // 输出 JSON 字符串
        System.out.println(jsonObject.toString());
        // 输出: {"isStudent":false,"name":"John Doe","age":30}
    }
}

2. 从字符串创建 JSONObject

import org.json.JSONObject;

public class JsonFromString {
    public static void main(String[] args) {
        String jsonString = "{\"city\":\"New York\",\"country\":\"USA\"}";
        
        // 从字符串创建 JSONObject
        JSONObject jsonObject = new JSONObject(jsonString);
        
        // 获取值
        String city = jsonObject.getString("city");
        String country = jsonObject.getString("country");
        
        System.out.println("City: " + city + ", Country: " + country);
        // 输出: City: New York, Country: USA
    }
}

3. 嵌套 JSON 对象

import org.json.JSONObject;

public class NestedJson {
    public static void main(String[] args) {
        JSONObject address = new JSONObject();
        address.put("street", "123 Main St");
        address.put("zip", "10001");
        
        JSONObject person = new JSONObject();
        person.put("name", "Alice");
        person.put("age", 25);
        person.put("address", address);
        
        System.out.println(person.toString(2)); // 参数2表示缩进2个空格
        /* 输出:
        {
          "name": "Alice",
          "age": 25,
          "address": {
            "street": "123 Main St",
            "zip": "10001"
          }
        }
        */
    }
}

4. 处理 JSON 数组

import org.json.JSONArray;
import org.json.JSONObject;

public class JsonArrayExample {
    public static void main(String[] args) {
        JSONObject person1 = new JSONObject();
        person1.put("name", "Tom");
        person1.put("age", 28);
        
        JSONObject person2 = new JSONObject();
        person2.put("name", "Jerry");
        person2.put("age", 26);
        
        // 创建 JSON 数组
        JSONArray jsonArray = new JSONArray();
        jsonArray.put(person1);
        jsonArray.put(person2);
        
        // 将数组放入 JSON 对象
        JSONObject root = new JSONObject();
        root.put("employees", jsonArray);
        
        System.out.println(root.toString(2));
        /* 输出:
        {
          "employees": [
            {
              "name": "Tom",
              "age": 28
            },
            {
              "name": "Jerry",
              "age": 26
            }
          ]
        }
        */
    }
}

5. 异常处理

import org.json.JSONException;
import org.json.JSONObject;

public class JsonExceptionHandling {
    public static void main(String[] args) {
        try {
            String invalidJson = "{name: 'John'}"; // 缺少引号
            
            JSONObject jsonObject = new JSONObject(invalidJson);
            System.out.println(jsonObject.toString());
        } catch (JSONException e) {
            System.err.println("JSON 解析错误: " + e.getMessage());
            // 输出: JSON 解析错误: Expected a ':' after a key at 6 [character 7 line 1]
        }
    }
}

注意事项

  1. org.json 是一个轻量级的 JSON 处理库,适合简单的 JSON 操作
  2. 对于更复杂的 JSON 处理,可以考虑使用 Jackson 或 Gson
  3. 在 Java 9+ 中,这个库可能需要在 module-info.java 中添加模块声明
  4. 该库不是线程安全的,如果需要在多线程环境中使用,需要自行同步

希望这些示例能帮助你理解如何使用 org.json.JSONObject 来处理 JSON 数据。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐