You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java/JavaFX读取JSON嵌套对象中的email字段?

解决Java读取嵌套JSON中email字段的问题

嘿,我一眼就瞅出问题所在啦!你现在直接从顶层的JSONObject里获取email字段肯定拿不到,因为email并不是顶层字段——它是嵌套在customer这个子JSON对象里的,和product_id、status不是平级的。

正确的读取步骤

  1. 先从顶层JSONObject中获取customer对应的子JSONObject
  2. 再从这个子对象里读取email字段

修改后的代码片段

把你代码里最后一行获取email的代码替换成下面的内容:

// 先获取嵌套的customer对象
JSONObject customerObj = myResponse.getJSONObject("customer");
// 从customer对象中读取email
System.out.println("Email : "+customerObj.getString("email"));

完整的修改后方法

public static void call_me() throws Exception {
    String url = "Link WEbsite/api/?apiKey=23459876";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // optional default is GET
    con.setRequestMethod("GET");
    //add request header
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    //print in String
    System.out.println(response.toString());
    //Read JSON response and print
    JSONObject myResponse = new JSONObject(response.toString());
    System.out.println("result after Reading JSON Response");
    System.out.println("Product Name : "+myResponse.getString("product_id"));
    System.out.println("status : "+myResponse.getString("status"));
    // 修改部分:先获取customer子对象,再读取email
    JSONObject customerObj = myResponse.getJSONObject("customer");
    System.out.println("Email : "+customerObj.getString("email"));
}

额外小提示

如果API返回的JSON中customer字段可能为null或者不存在,为了避免抛出异常,你可以用optJSONObject方法来安全获取:

JSONObject customerObj = myResponse.optJSONObject("customer");
if (customerObj != null) {
    System.out.println("Email : "+customerObj.optString("email", "未获取到邮箱"));
} else {
    System.out.println("Email : 无客户信息");
}

内容的提问来源于stack exchange,提问作者Indi Jaka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:48:45