JSONObject必须在字符1 [字符2第1行]处以"{"开头 [英] JSONObject must begin with '{' at character 1[character 2 line 1]

查看:147
本文介绍了JSONObject必须在字符1 [字符2第1行]处以"{"开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首次发布到stackoverflow,抱歉,如果发布格式错误.如果可以帮我解决问题,就不会介意反馈.

尝试从WU(天气地下)接收JSON. 这是JSON:

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)

如果我更改JSONObject jSon = new JSONObject(output.trim());JSONObject jSon = new JSONObject(br); 相反,我得到了错误:

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)

如果我将JSONObject(br);更改为JSONObject(br.readLine()); 我收到此错误:

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)

当我打印ln时,

outputbr都给出相同的输出.它与我期望的JSON完全相同.

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

我还尝试仅调用响应",仅调用版本",仅调用条件"和当前观察",并且由于我看不到任何[],所以我认为它们没有JSONArray.

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.

System.out.println(output)/(br)仅在代码中以测试要打印的内容.他们都是一样的.除了我打印输出时.开头有一个空白,表示output.trim()不会被删除...因此我总是会收到must start with '{'错误.

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.

我显然误解了整个JSONObject/Array.get序列.或HttpRequest中的内容不正确.即使当我打印broutput时,这也是我所期望的.

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.

我相信我也已经遍历了所有stackoverflow线程,并尝试了所有可能的org.json答案.

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

发现此选项对于不同的选项最为有用,但没有任何效果: JSONObject文本必须以'{'

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

向所有解决方案开放,但希望保留在org.json中,如果需要可以获取GSON,但可以肯定的是我只是误解了整个过程,而且很容易解决..

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

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

按预期打印出完美的JSON..但是:

prints out the JSON perfect as expected.. but:

System.out.println(br);

打印出以下内容:

java.io.BufferedReader@3108bc

一遍又一遍. 所以:

JSONObject jSon = new JSONObject(br);

什么也找不到.

推荐答案

在我以前的答案中编辑代码并将代码添加到我的先前答案中,当您在Android中进行编码时谁在帮助我,我将添加另一个解决方案,这次使用 http client

Instead edit and adding code to my previous answer who was helping when you coding in Android , i will add another solution , this time using http client

我不会在同一个文件中执行所有操作,但是我创建了两个文件,一个正在解析(可重用),另一个正在使用第一个(客户端请求).

I din't do everything in the same file , but i created two files , one of parsing (reusable) and another one who is using the first one (client request) .

  • JSONParser

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public JSONParser() {
    }
    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method) {
        // Making HTTP request
        try {
            // check for request method
            if("POST".equals(method)){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);  
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }else if("GET".equals(method)){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
         e.printStackTrace();
        }
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
             e.printStackTrace();
        }
        return jObj; 
    }
}

  • 客户

    import java.io.IOException;
    import java.util.Iterator;
    import org.json.JSONException;
    import org.json.JSONObject;
    public class Client {
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            try {
                getJsonHttp();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        public static void getJsonHttp() throws IOException, JSONException {
                JSONParser jsp = new JSONParser();
                String url ="http://api.wunderground.com/api/<key>/conditions/q/Australia/Brisbane.json";
                    JSONObject obj = jsp.makeHttpRequest(url, "GET");
                    JSONObject disp = obj.getJSONObject("current_observation");
                   JSONObject des = disp.getJSONObject("display_location");
                   JSONObject jObject = new JSONObject(des.toString().trim());
                   Iterator<?> keys = jObject.keys();
                   while( keys.hasNext() ) {
                       String key = (String)keys.next();
                          if("full".equals(key) || "city".equals(key) || "state".equals(key) || "state_name".equals(key)){
                              System.out.println(jObject.get(key).toString());
                          }
                   }   
        }
    }
    

  • 如果执行代码,则会得到以下结果:

    If you execute the code , you will get this result:

    您应该添加到构建路径中的库是:

    THe libraries you should add to the build path are :

    我从这里下载它: HttpComponents下载

    这篇关于JSONObject必须在字符1 [字符2第1行]处以"{"开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆