在 IntelliJ IDEA 中 , 选择 " 菜单栏 | File | New Project " 选项 ,
在弹出的 " New Project " 对话框 中 , 选择 Gradle 工程 ;
输入工程名 , 点击 " Finish " 按钮 , 完成创建 ;
在 build.gradle 构建脚本 中 导入 org.json:json 依赖 ;
dependencies {// json 依赖库implementation 'org.json:json:20210307'
}
在下面的代码中 , 分别 创建 JSON 对象 和 JSON 数组 , 以及 解析 JSON 字符串为 JSON 对象 ;
JSON 对象 和 JSONArray 数组对象 可以直接转为 JSON 字符串 ;
代码示例 :
import org.json.*;public class JsonDemo {public static void main(String[] args) {// 创建 JSON 对象JSONObject student = new JSONObject();student.put("name", "Tom");student.put("age", 18);// 打印 JSON 对象System.out.println(student);// 创建一个 JSON 数组JSONArray students = new JSONArray();students.put("Tom");students.put("Jerry");students.put("Jack");// 打印 JSON 数组System.out.println(students);// 解析 JSON 字符串String jsonStr = "{\"name\":\"Tom\", \"age\":18}";JSONObject obj = new JSONObject(jsonStr);String name = obj.getString("name");int age = obj.getInt("age");// 打印 解析 JSON 字符串 结果System.out.println("name: " + name);System.out.println("age: " + age);}
}
执行结果 :
{"name":"Tom","age":18}
["Tom","Jerry","Jack"]
name: Tom
age: 18