代码之家  ›  专栏  ›  技术社区  ›  Amir

如何解析URL请求的JSON结果?

  •  0
  • Amir  · 技术社区  · 7 年前

    我是android和java的新手。我想获得一个url请求(结果是JSON)并对其进行解析(例如从yahoo api获得JSON天气)。

    public static String getStringFromURL(String urlString) throws IOException {
        HttpURLConnection urlConnection;
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.setDoOutput(true);
        urlConnection.connect();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
        char[] buffer = new char[1024];
        String outputString;
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            builder.append(line).append("\n");
        }
        bufferedReader.close();
        outputString = builder.toString();
        return outputString;
    }
    
    public void setWeather (View view) throws IOException, JSONException {
        String json = getStringFromURL("https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='Esfahan')&format=json");
        JSONObject jso = new JSONObject(json);
        JSONObject query = jso.getJSONObject("query");
        JSONObject result = query.getJSONObject("results");
        JSONObject channel = result.getJSONObject("channel");
        JSONObject windI = channel.getJSONObject("wind");
        JSONObject location = channel.getJSONObject("location");
        String last = "";
        last = location.getString("city");
        TextView tv = (TextView) findViewById(R.id.textView);
        tv.setText(last);
    }
    

    当我在设备上运行此应用程序时,应用程序崩溃。 在Android Monitor上写入错误:

    2 回复  |  直到 7 年前
        1
  •  1
  •   KingKongCoder    7 年前

    getStringFromURL("https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='Esfahan')&format=json");
    

    tv.setText(last);
    

    在ui线程上运行。所有这些管理都是由Asnyctask完成的,所以您不需要担心线程管理,只需知道使用哪种方法即可。 Asynctask Android documentation

        2
  •  1
  •   Samarth    7 年前

    在android的情况下,有一个概念你必须遵循,所有耗时的任务都需要在一个单独的线程上进行,而这个线程不会阻塞你的UI线程。所有IO调用或重操作调用都应该转到一个单独的线程。

    有关如何进行网络操作的更多信息,请参阅《Android开发者指南》 在这里( https://developer.android.com/training/basics/network-ops/connecting.html )并遵循此文档。