【问题标题】:org.json.JSONException: Value HTTP of type java.lang.String cannot be converted to JSONObjectorg.json.JSONException:java.lang.String 类型的值 HTTP 无法转换为 JSONObject
【发布时间】:2020-11-30 05:43:55
【问题描述】:

我对 Json 解析和使用 API 非常陌生,所以我不知道为什么会发生这种情况。如果您能帮助解决问题,我们将不胜感激。

现在解决问题。

在创建我的 Springboot 应用程序时,我在尝试显示来自 openweathermap 的 API 数据时遇到了一个我无法弄清楚的 JSONException。

org.json.JSONException:java.lang.String 类型的 HTTP 值无法转换为 JSONObject

好像发生在这一行

 String city = getCityById(id);

这是完整的 Java 文件(我的 api 密钥已编辑)

package Homework4_API.Homework4.controllers;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;

@RestController
public class MainController {

    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public ModelAndView get(@RequestParam("id") String id) {
        ModelAndView mv = new ModelAndView ("redirect:/");
        String city = getCityById(id);
        try{
            JSONObject json = new JSONObject(city);
            mv.addObject("name", json.getString("name"));
            mv.addObject("temperature", json.getJSONObject("main").get("temp").toString());
            mv.addObject("feels_like", json.getJSONObject("main").get("feels_like").toString());
            mv.addObject("humidity", json.getJSONObject("main").get("humidity").toString());
            mv.addObject("weather", json.getJSONObject("weather").get("description").toString());

        }
        catch (Exception e){
            System.out.println(e.toString());
        }

        return mv;
    }

    private String getCityById(String id){
        try {
            String apiKey = "[redacted]";
            URL URLForRequest = new URL("https://api.openweathermap.org/data/2.5/weather?q=" + id + "&appid=" + apiKey);

            HttpsURLConnection connection = (HttpsURLConnection) URLForRequest.openConnection();
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null){
                    response.append(line);
                }
                in.close();
                return response.toString();
            }
            else {
                return "HTTP SAID NOOOOOO!!";
            }
        }
        catch (Exception e){
            return "HTTP Said No";
        }
    }
}

class City
{
    private String City;

    public City(){
        City = "DEFAULT";
    }

    public City(String c) {
        City = c;
    }

    public String getCity() {
        return City;
    }

}

HTML 文件

<!DOCTYPE html>
<html>
<head>

    <title></title>
    <style><%@include file ="../css/style.css"%></style>

</head>

<body>

    <h1>Please Select A City</h1>
    <form method="get" action="/get/">
        <select name = "id">
            <option value ="1">Houston</option>
            <option value ="2">San Antonio</option>
            <option value ="3">Dallas</option>
            <option value ="4">Austin</option>
            <option value ="5">Fort Worth</option>
            <option value ="6">Phoenix</option>
            <option value ="7">Atlanta</option>
            <option value ="8">Chicago</option>
            <option value ="9">Los Angles</option>
            <option value ="10">New York City</option>
        </select>
        <input type="submit" value="Submit">
    </form>

    <div>
        <h2>City</h2> <h3><%=request.getParameter("name")%></h3>
        <h2>Temperature</h2> <h3><%=request.getParameter("temperature")%></h3>
        <h2>Feels Like</h2> <h3><%=request.getParameter("feels_like")%></h3>
        <h2>Humidity</h2> <h3><%=request.getParameter("humidity")%></h3>
        <h2>Weather</h2> <h3><%=request.getParameter("weather")%></h3>
    </div>

    <hr>
    <div>
        <h2>Previously Requested Cities</h2>
    </div>
    </hr>

</body>

</html>

XML 文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>Homework4_API</groupId>
    <artifactId>Homework4</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Homework4</name>
    <description>Spring boot for homework 4</description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

        <dependency>
            <groupId>com.vaadin.external.google</groupId>
            <artifactId>android-json</artifactId>
            <version>0.0.20131108.vaadin1</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>com.vaadin.external.google</groupId>
            <artifactId>android-json</artifactId>
            <version>0.0.20131108.vaadin1</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>



    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

我确实有一个没有任何内容的 css 文件、一个应用程序文件和一个主运行文件,但我认为他们没有做任何事情来导致这个特定问题。

【问题讨论】:

    标签: java json spring spring-boot jsonexception


    【解决方案1】:

    返回一个 POJO,如果触发了 Else 条件,则在其中放入一个异常字段并填充该异常字段。如果一切正常,则返回填充对象。

    【讨论】:

    • 我将如何在“getCityById”类中执行此操作?很抱歉有额外的问题,只是对如何做到这一点感到困惑。
    • 在try块外创建StringBuilder,追加response.append(""HTTP SAID NOOOOOO!!"");在 else 块中返回 response.toString(),,,
    • 仍然得到相同的异常。我有“StringBuilder 测试 = new StringBuilder();”在 try 块之前。虽然我有 "test.append("HTTP said NOOOO!"); " 然后 "return test.toString();"在 else 语句中。也许我只是在某个地方犯了一个愚蠢的错误?
    • 在附加到 Stringbuilder 时,当 IF 块中的情况正常时检查“行”中的内容。将类似的 {Key: value} 放在 else 块中
    【解决方案2】:

    查看您的代码,看起来 return "HTTP SAID NOOOOOO!!"; 正在执行,这不是 JSON,所以它会抛出错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多