我正在尝试使用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

最佳答案

你可以试试看

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

08-16 16:11