【问题标题】:How to read JSON file from URL?如何从 URL 读取 JSON 文件?
【发布时间】:2019-09-14 09:23:09
【问题描述】:

我正在尝试使用 gson 从 URL 读取 json,但似乎有问题。

这是我的代码:

String url = "...";
com.google.gson.JsonObject jsonObject = new JsonParser().parse(url).getAsJsonObject();

String fajr = jsonObject.getAsJsonObject("data").getAsJsonObject("timings").get("Fajr").getAsString();
System.out.println(fajr);

错误:

Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 6 path $
    at com.google.gson.JsonParser.parse(JsonParser.java:65)
    ...
Caused by: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 6 path $
    at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1568)
    ...
    at com.google.gson.JsonParser.parse(JsonParser.java:60)
    ... 2 more

【问题讨论】:

  • 您不能直接将 url 传递给 JsonParser 。您必须从 url 获得响应并将该响应传递给 JsonParser

标签: java android json gson


【解决方案1】:

你可以试试这个

   try {

    String link = "http://api.aladhan.com/v1/timingsByCity?city=Penang&country=Malaysia&method=8";
    URL url = new URL(link);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    if (responseCode == 200) {
    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
    String output;
    String totalString = "" ;
    while ((output = br.readLine()) != null) {
    totalString += output;
    }
    System.out.println(totalString);


    com.google.gson.JsonObject jsonObject = new JsonParser().parse(totalString).getAsJsonObject();

    String fajr = jsonObject.getAsJsonObject("data").getAsJsonObject("timings").get("Fajr").getAsString();
    System.out.println(fajr);
    }
    }
    catch(Exception e) 
    {
    e.printStackTrace();
    }

【讨论】:

    猜你喜欢
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    相关资源
    最近更新 更多