【问题标题】:Android code for showing List View of JSON用于显示 JSON 列表视图的 Android 代码
【发布时间】:2019-03-18 13:25:01
【问题描述】:

如何编写 java 代码以显示来自 "http://services.groupkt.com/country/search?text=un" 的 JSON 数据?我想查看数据的列表视图。

下面的尝试似乎不起作用:

private String loadJSON(String jsonURL) throws IOException {

    URL url = new URL(jsonURL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    conn.connect();

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    StringBuilder response = new StringBuilder();

    while ((line = in.readLine()) != null) {

        response.append(line);
    }

    in.close();
    return response.toString();
}

【问题讨论】:

  • 您是否收到任何错误或任何回报?但是,为什么不使用更易于使用且易于获取值的 GSON 呢?这听起来像是一种旧方法。
  • 没有错误。只是应用顶部带有横幅的白屏

标签: android json listview


【解决方案1】:

工薪阶层示例:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonReader {

  private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
  }

  public static void main(String[] args) throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("https://graph.facebook.com/19292868552");
    System.out.println(json.toString());
    System.out.println(json.get("id"));
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 2015-07-16
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多