org.json.JSONException: Value HTTP of type java.lang.String cannot be converted to JSONObject

788 Views Asked by At

I'm pretty new to Json parsing, and working with API's so I have little idea on why this is happening. It would be greatly appreciated if you could help solve the issue.

Now onto the problem.

While creating my Springboot application I was getting a JSONException that I just can't figure out, while trying to display API data from openweathermap.

org.json.JSONException: Value HTTP of type java.lang.String cannot be converted to JSONObject

It seems to be happening at this line

 String city = getCityById(id);

Here's the full Java file (with my api key redacted)

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 File

<!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 file

<?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>

I do have a css file with nothing in it, an application file, and main run file, but I don't think they're doing anything to cause this specific problem.

2

There are 2 best solutions below

0
On

Looking at your code it looks like return "HTTP SAID NOOOOOO!!"; is getting executed, Which isn't JSON so it is throwing Error.

4
On

Return a POJO, Put a exception field in it if Else condition is triggered and fill this exception field. If everything if fine return filled up object.