简体   繁体   English

如何从URL读取JSON文件?

[英]How to read JSON file from URL?

I am trying to read json from URL with gson but there seems to be a problem. 我正在尝试使用gson从URL读取json,但似乎存在问题。

Here is my code: 这是我的代码:

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

The errors: 错误:

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

You can Try this 你可以试试看

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM