org.json.JSONException: JSONObject["userId"] 未找到。 .JSONException [关闭]

Posted

技术标签:

【中文标题】org.json.JSONException: JSONObject["userId"] 未找到。 .JSONException [关闭]【英文标题】:org.json.JSONException: JSONObject["userId"] not found. .JSONException [closed] 【发布时间】:2021-10-04 13:32:59 【问题描述】:

现在我的问题是 json 对象找不到我不知道为什么的密钥。但是正如您在错误中看到的那样,响应已打印出所有键。

package com.ar.team.company.project;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main 

    public static void main(String[] args) 
        try 
            Main.readJsonData();
         catch (Exception e) 
            e.printStackTrace();
        
    

    public static void readJsonData() throws Exception 
        // Initializing:
        String url = "https://jsonplaceholder.typicode.com/posts/1"; // Our url.
        URL obj = new URL(url); // Our url object(To open connection from it.).
        HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // Our 
        httpURLConnection to connect to json.
        // Optional default is GET for getting the data:
        con.setRequestMethod("GET");
        // Add request header:
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        // Getting the response code:
        int responseCode = con.getResponseCode();
        // Show to user the data:
        System.out.println("Sending 'GET' request to URL: " + url);
        System.out.println("Response code: " + responseCode);
        // Start read the data:
        BufferedReader in = new BufferedReader(new                         
        InputStreamReader(con.getInputStream())); // Our buffered reader.
        String inputLine; // For checking the new line.
        StringBuilder response = new StringBuilder(); // Here is our reading data.
        while ((inputLine = in.readLine()) != null) 
            response.append(inputLine); // Append the data for response(StringBuilder).
        
        in.close(); // Closing the buffered reader.
        // Print in String:
        System.out.println("The response data: " + response);
        // Read JSON response and print:
        JSONObject myResponse = new JSONObject(response);
        System.out.println("Result After Reading JSON Response:".toUpperCase());
        // All Result:
        System.out.println("UserId: " + myResponse.getString("userId"));
        System.out.println("Id: " + myResponse.getString("id"));
        System.out.println("Title: " + myResponse.getString("title"));
        System.out.println("Body: " + myResponse.getString("body"));
    


错误

Sending 'GET' request to URL: https://jsonplaceholder.typicode.com/posts/1
Response code: 200
The response data:   "userId": 1,  "id": 1,  "title": "sunt aut facere repellat 
provident occaecati excepturi optio reprehenderit",  "body": "quia et suscipit\nsuscipit 
recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas 
totam\nnostrum rerum est autem sunt rem eveniet architecto"
RESULT AFTER READING JSON RESPONSE:
org.json.JSONException: JSONObject["userId"] not found.
   at org.json.JSONObject.get(JSONObject.java:516)
   at com.ar.team.company.project.Main.readJsonData(Main.java:48)
   at com.ar.team.company.project.Main.main(Main.java:14)

【问题讨论】:

请不要为了破坏最小长度过滤器而破坏您的问题。 好的,谢谢。我很抱歉 【参考方案1】:

代码错误:

    错误:JSONException: JSONObject["userId"] not found.

    response 是一个StringBuilder,所以new JSONObject(response) 正在调用JSONObject(Object bean) 构造函数。由于StringBuilder 不是Java Bean,它没有属性,JSONObject 为空。

    将代码更改为new JSONObject(response.toString()),以便调用JSONObject(String source) 构造函数。

    错误:JSONException: JSONObject["userId"] not a string.

    userId 的值是一个 JSON 数字,因此您必须调用其中一种 get 方法来检索数值,例如getInt(String key),或任何其他人:getLonggetBigIntegergetDoublegetFloatgetNumber

    将代码更改为getInt("userId")

    错误:JSONException: JSONObject["id"] not a string.

    同 #2:将代码更改为 getInt("id")

【讨论】:

以上是关于org.json.JSONException: JSONObject["userId"] 未找到。 .JSONException [关闭]的主要内容,如果未能解决你的问题,请参考以下文章

org.json.JSONException: org.json.JSONArray 类型的Value[] 无法转换为 JSONObject

org.json.JSONException:电子邮件没有值

org.json.JSONException:名称没有值

org.json.JSONException:overview_polyLine 没有值

类型 org.json.JSONException 被定义多次

在尝试解析 JSON 数据 W/System.err 时出现此错误:org.json.JSONException:对客户没有价值