JSONObject必须以字符1 [字符2第1行]

时间:2017-06-17 07:10:48

标签: java json apache

第一次发布到stackoverflow,抱歉如果帖子格式错误。如果这有助于我的问题支出,我会介意反馈。

尝试从WU(Weather Underground)接收JSON。 这是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":""
  }
}

这就是我试图调用它并使用它的方式:

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();
    }
}

使用此当前代码,我收到此错误:

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); 我反而得到错误:

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()); 我收到这个错误:

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完全相同。

我也尝试过只调用“响应”,只调用“版本”,只调用“条件”和“当前观察”,因为我看不到任何[]我认为它们不是JSONArray的。

System.out.println(output)/(br)就在代码中,用于测试打印出来的内容。它们都是一样的。除非我打印输出。开头有一个空格output.trim()没有摆脱......所以我总是得到must start with '{'错误。

我显然误解了整个JSONObject / Array.get序列。或HttpRequest中的某些内容不对。即使我打印broutput时,我也期待它。

我相信我也经历过关于此问题的所有stackoverflow线程,并尝试了所有可能的org.json答案。

发现这个对于不同的选项最有用,但没有任何效果: JSONObject text must begin with '{'

对所有解决方案开放但是想留在org.json中,如果需要可以获得GSON但​​是我肯定误解了整个事情并且很容易解决..

修改

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

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

System.out.println(br);

打印出以下内容:

java.io.BufferedReader@3108bc

一遍又一遍。 这样:

JSONObject jSon = new JSONObject(br);

找不到任何东西。

3 个答案:

答案 0 :(得分:0)

正确的陈述是

JSONObject jSon = new JSONObject(br);

您收到Exception in thread "main" org.json.JSONException: JSONObject["version"] not found.错误,因为version不是直接对象。它只是response对象的一个​​属性,city用于嵌套的display_location对象。所以,以类似的方式检索它。 首先是response对象,然后是其属性version

答案 1 :(得分:0)

有时,当您开始专门针对移动设备进行编码时,您会对最终结果感兴趣,而不必关注已弃用以及什么是新内容。 您不再支持您使用的库,请阅读这篇文章Apache HTTP Client Removal

所以也许在阅读之后你会感兴趣,有什么替代方案? 一个可以允许你这样做的图书馆是排球,  是一个HTTP库,使Android应用程序的网络更容易,最重要的是,更快。您可以在Transmitting Network Data Using Volley

找到图书馆的所有好处

我不再使用eclipse来开发android了,现在我正在使用 Android Studio ,我想展示我是如何使用IDE和排球库制作你的应用程序的:

添加到build.gradle的依赖关系

 dependencies {
    compile 'com.android.volley:volley:1.0.0'
}

<强> MainActivity

     package com.example.frank.wunderground;

    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.widget.Toast;

    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.JsonObjectRequest;
    import com.android.volley.toolbox.Volley;

    import org.json.JSONException;
    import org.json.JSONObject;
    public class MainActivity extends AppCompatActivity {
        final String url = "http://api.wunderground.com/api/<your_key>/conditions/q/Australia/Brisbane.json";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            RequestQueue queue = Volley.newRequestQueue(this);
    // prepare the Request
            JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                    new Response.Listener<JSONObject>()
                    {
                        @Override
                        public void onResponse(JSONObject response) {
                            // display response
                            //Log.d("Berly", response.toString());
                            //Toast.makeText(getApplicationContext(), response.toString() , Toast.LENGTH_LONG).show();


                            try {
//version is not a Object it was a mistake in your code
                              //  JSONObject fullJson = response.getJSONObject("version"); 
                                JSONObject currentObservation = response.getJSONObject("current_observation");
                                JSONObject displayLocation = currentObservation.getJSONObject("display_location");
                               String full = displayLocation.getString("full");
                                Log.d("Berly", full.toString());
                                Toast.makeText(getApplicationContext(), "Berly: "+full.toString() , Toast.LENGTH_LONG).show();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                        }
                    },
                    new Response.ErrorListener()
                    {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                           // Log.d("Error.Response", error);
                        }
                    }
            );
    // add it to the RequestQueue
            queue.add(getRequest);
        }
    }

结果 Console log

full json file response

your desiderate result

答案 2 :(得分:-1)

相反编辑并添加代码到我以前的答案,当你在Android中编码时,我会添加另一个解决方案,这次使用 http客户端

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

  • <强> 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());
                          }
                   }   
        }
    }
    

如果执行代码,您将得到以下结果:

enter image description here

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

我是从这里下载的:HttpComponents Downloads

enter image description here