Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

java - JSONObject must begin with '{' at character 1[character 2 line 1]

First time posting to stackoverflow, sorry if post format is wrong. wouldnt mind feedback on it if that helps with my question outlay.

Trying to receive the JSON from WU(Weather Underground). This is the JSON:

{
  "response":{
    "version":"0.1",
    "termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
    "features":{
      "conditions":1
    }
  },
  "current_observation":{
    "image":{
      "url":"http://icons.wxug.com/graphics/wu2/logo_130x80.png",
      "title":"Weather Underground",
      "link":"http://www.wunderground.com"
    },
    "display_location":{
      "full":"Brisbane, Australia",
      "city":"Brisbane",
      "state":"QNS",
      "state_name":"Australia",
      "country":"AU",
      "country_iso3166":"AU",
      "zip":"00000",
      "magic":"15",
      "wmo":"94576",
      "latitude":"-27.46999931",
      "longitude":"153.02999878",
      "elevation":"14.0"
    },
    "observation_location":{
      "full":"Liberte Weather, Brisbane, ",
      "city":"Liberte Weather, Brisbane",
      "state":"",
      "country":"AU",
      "country_iso3166":"AU",
      "latitude":"-27.476187",
      "longitude":"153.037369",
      "elevation":"0 ft"
    },
    "estimated":{

    },
    "station_id":"IBRISBAN101",
    "observation_time":"Last Updated on June 17, 4:07 PM AEST",
    "observation_time_rfc822":"Sat, 17 Jun 2017 16:07:44 +1000",
    "observation_epoch":"1497679664",
    "local_time_rfc822":"Sat, 17 Jun 2017 16:08:10 +1000",
    "local_epoch":"1497679690",
    "local_tz_short":"AEST",
    "local_tz_long":"Australia/Brisbane",
    "local_tz_offset":"+1000",
    "weather":"Mostly Cloudy",
    "temperature_string":"71.6 F (22.0 C)",
    "temp_f":71.6,
    "temp_c":22.0,
    "relative_humidity":"75%",
    "wind_string":"From the WNW at 6.8 MPH",
    "wind_dir":"WNW",
    "wind_degrees":292,
    "wind_mph":6.8,
    "wind_gust_mph":0,
    "wind_kph":10.9,
    "wind_gust_kph":0,
    "pressure_mb":"1016",
    "pressure_in":"30.01",
    "pressure_trend":"0",
    "dewpoint_string":"63 F (17 C)",
    "dewpoint_f":63,
    "dewpoint_c":17,
    "heat_index_string":"NA",
    "heat_index_f":"NA",
    "heat_index_c":"NA",
    "windchill_string":"NA",
    "windchill_f":"NA",
    "windchill_c":"NA",
    "feelslike_string":"71.6 F (22.0 C)",
    "feelslike_f":"71.6",
    "feelslike_c":"22.0",
    "visibility_mi":"6.2",
    "visibility_km":"10.0",
    "solarradiation":"--",
    "UV":"0",
    "precip_1hr_string":"-999.00 in ( 0 mm)",
    "precip_1hr_in":"-999.00",
    "precip_1hr_metric":" 0",
    "precip_today_string":"0.00 in (0 mm)",
    "precip_today_in":"0.00",
    "precip_today_metric":"0",
    "icon":"mostlycloudy",
    "icon_url":"http://icons.wxug.com/i/c/k/mostlycloudy.gif",
    "forecast_url":"http://www.wunderground.com/global/stations/94576.html",
    "history_url":"http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=IBRISBAN101",
    "ob_url":"http://www.wunderground.com/cgi-bin/findweather/getForecast?query=-27.476187,153.037369",
    "nowcast":""
  }
}

This is how im trying to call it and work with it:

public static void getJsonHttp() throws IOException, JSONException {
    String output; // contains received JSON 
    String full; // city,country
    String city; // city
    String state; // state
    String stateName; // state name
    try {

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet getRequest = new HttpGet(
                "http://api.wunderground.com/api/<MY API KEY>/conditions/q/Australia/Brisbane.json");
        getRequest.addHeader("accept", "application/json");

        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }
        BufferedReader br = new BufferedReader(
                new InputStreamReader((response.getEntity().getContent())));

        while ((output = br.readLine()) != null) {

            // System.out.println(output);
            // System.out.println(br);
            JSONObject jSon = new JSONObject(output.trim());
            // System.out.println(jSon);
            JSONObject fullJson = jSon.getJSONObject("version");
            JSONObject currentObservation = fullJson.getJSONObject("current_observation");
            JSONObject displayLocation = currentObservation.getJSONObject("display_location");

            full = displayLocation.getString("full");
            city = displayLocation.getString("city");
            state = displayLocation.getString("state");
            stateName = displayLocation.getString("state_name");

            System.out.println(full);
            System.out.println(city);
            System.out.println(state);
            System.out.println(stateName);

        }
    } catch (ClientProtocolException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();
    }
}

With this current code I am getting this error:

Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:451)
    at org.json.JSONObject.<init>(JSONObject.java:196)
    at org.json.JSONObject.<init>(JSONObject.java:320)
    at mainCommands.JsonConverter.getJsonHttp(JsonConverter.java:74)
    at mainCommands.JsonConverter.main(JsonConverter.java:41)

If I change the JSONObject jSon = new JSONObject(output.trim()); to JSONObject jSon = new JSONObject(br); I instead get the error:

Exception in thread "main" org.json.JSONException: JSONObject["version"] not found.
    at org.json.JSONObject.get(JSONObject.java:472)
    at org.json.JSONObject.getJSONObject(JSONObject.java:637)
    at mainCommands.JsonConverter.getJsonHttp(JsonConverter.java:76)
    at mainCommands.JsonConverter.main(JsonConverter.java:41)

If I change the JSONObject(br); to JSONObject(br.readLine()); I get this error:

Exception in thread "main" org.json.JSONException: A JSONObject text must end with '}' at 2 [character 3 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:451)
    at org.json.JSONObject.<init>(JSONObject.java:202)
    at org.json.JSONObject.<init>(JSONObject.java:320)
    at mainCommands.JsonConverter.getJsonHttp(JsonConverter.java:74)
    at mainCommands.JsonConverter.main(JsonConverter.java:41)

both output and br give the same output when I print ln. its the exact same as the JSON above which im expecting.

I have also tried only calling "response", only calling "version", only calling "conditions" and "current observation" and since I cant see any [] i assume they arent JSONArray's.

The System.out.println(output)/(br) are just in the code to test what prints out. and theyre both the same. except when I print output. there is a whitespace at the beginning that output.trim() doesnt get rid of... so im always getting the must start with '{' error.

I’m obviously misunderstanding the whole JSONObject/Array.get sequence. or something in the HttpRequest isnt right. even though when I println the br or output it is what I’m expecting it to be.

I believe I have also gone through all stackoverflow threads about this aswell and tried all possible org.json answers.

found this one the most useful for different options but nothing worked: JSONObject text must begin with '{'

open to all solutions but would like to stay within org.json, can get GSON if needed but surely i have just misunderstood the whole thing and its an easy fix..

EDIT:

System.out.println(br.readLine());

prints out the JSON perfect as expected.. but:

System.out.println(br);

prints out the following:

java.io.BufferedReader@3108bc

over and over again. so:

JSONObject jSon = new JSONObject(br);

wouldnt find anything.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The correct statement would be

JSONObject jSon = new JSONObject(br);

You are getting the Exception in thread "main" org.json.JSONException: JSONObject["version"] not found. error because version is not a direct object. It is only an attribute of the response object as city is for the nested display_location object. So, retrieve it in a similar fashion. First, response object and then its attribute version.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...