简体   繁体   中英

How to read JSON file from URL?

I am trying to read json from URL with gson but there seems to be a problem.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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