首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >org.json.JSONException: JSONObject["userId"]没有找到。.JSONException

org.json.JSONException: JSONObject["userId"]没有找到。.JSONException
EN

Stack Overflow用户
提问于 2021-07-28 19:57:10
回答 1查看 1.9K关注 0票数 0

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

代码语言:javascript
复制
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"));
    }

}

误差

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-28 20:18:29

代码中的错误:

  1. Error: JSONException: JSONObject["userId"] not found.

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

将代码更改为new JSONObject(response.toString()),因此它称为JSONObject(String source) JSONObject(String source)

  1. Error: JSONException: JSONObject["userId"] not a string.

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

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

  1. Error: JSONException: JSONObject["id"] not a string.

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68566661

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档