温馨提示×

java怎么取jsonobject里的数据

小亿
95
2023-12-15 22:11:30
栏目: 编程语言

在Java中,可以使用org.json库来解析JSON数据。以下是一个例子,展示了如何从JSON对象中获取数据:

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

public class Main {
    public static void main(String[] args) {
        String jsonStr = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";

        // 将JSON字符串转换为JSONObject
        JSONObject jsonObj = new JSONObject(jsonStr);

        // 从JSONObject中获取数据
        String name = jsonObj.getString("name");
        int age = jsonObj.getInt("age");
        String city = jsonObj.getString("city");

        // 打印获取到的数据
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("City: " + city);
    }
}

上述代码将输出以下结果:

Name: John
Age: 30
City: New York

请注意,如果JSON中的键不存在,或者类型不匹配,将会抛出异常。因此,在使用这些方法之前,最好先检查键是否存在或者使用try-catch块来处理异常。

0