【问题标题】:Android JSON Parser From URL (NON DEPECREATED)来自 URL 的 Android JSON 解析器(未弃用)
【发布时间】:2026-01-13 20:30:02
【问题描述】:

好的,我的智慧快到此为止了。我一直在关注代码示例并阅读有关如何点击 URL 并在该 Web 请求之后读取 JSON 对象的线程。但是这些示例似乎都使用了 HttpClient 和 HttpResponse,android studio 说它已被弃用。 Android API 说要使用 URL 连接,但我似乎无法理解如何将模式与 URLConnection 一起使用。

那么我如何使用 URLConnection 来点击一个 URL,然后读取 JSON 对象。我可以在以后反序列化自己,因为 JSONObject 不被弃用。我正在为如何发起网络请求而苦苦挣扎。

谁有代码sn-ps?样品?网上有资料吗?

【问题讨论】:

标签: android json android-studio


【解决方案1】:

来自this sample project 来自this book,这里有一个线程使用HttpURLConnection 加载最新的 Stack Overflow 问题并使用 Gson 解析它们:

/***
  Copyright (c) 2013-2014 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  From _The Busy Coder's Guide to Android Development_
    http://commonsware.com/Android
 */

package com.commonsware.android.hurl;

import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.Gson;
import de.greenrobot.event.EventBus;

class LoadThread extends Thread {
  static final String SO_URL=
      "https://api.stackexchange.com/2.1/questions?"
          + "order=desc&sort=creation&site=*&tagged=android";

  @Override
  public void run() {
    try {
      HttpURLConnection c=
          (HttpURLConnection)new URL(SO_URL).openConnection();

      try {
        InputStream in=c.getInputStream();
        BufferedReader reader=
            new BufferedReader(new InputStreamReader(in));
        SOQuestions questions=
            new Gson().fromJson(reader, SOQuestions.class);

        reader.close();

        EventBus.getDefault().post(new QuestionsLoadedEvent(questions));
      }
      catch (IOException e) {
        Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
      }
      finally {
        c.disconnect();
      }
    }
    catch (Exception e) {
      Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
    }
  }
}

这里,SOQuestions 是 Stack Exchange 问题 API 的 Gson 注释类,我正在使用 greenrobot 的 EventBus 将结果传递给片段。当然,您可以用自己的替换 Stack Exchange API URL,并且需要解析它的 JSON 输出。

我不知道有多少 Android 开发人员不再使用 JSONObject,因为 Gson、Jackson 等提供了更好的选择,但您需要将 InputStream 读入 String 以传递给适当的JSONObject 构造函数。

您也可以考虑使用高阶方法。例如,this sample app 是第一个使用 Square 的 Retrofit 库来联系 Stack Exchange API Web 服务的克隆,而不是HttpUrlConnection

【讨论】:

  • Gson 和 Json 有什么区别?
  • @Arlind:JSON 是一种数据格式。 Google's Gson 是一个解析 JSON 的库。