Gson – Read and Parse JSON from URL example shows how to read and parse JSON from a URL using the Gson library in Java.
How to parse JSON from a URL?
The Gson library provides methods to read and parse JSON in a variety of ways, including from a URL. The process of parsing JSON from URLs is almost the same as reading it from a file or from a string.
All we need to do is to read the URL using a reader, then use the fromJson
method of the Gson class that accepts a reader object and parses the JSON from reading it.
Here is an example program that reads and parses a JSON from the World time API URL.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package com.javacodeexamples.gsonexamples; import java.io.InputStreamReader; import java.net.URL; import com.google.gson.Gson; import com.google.gson.JsonObject; public class GsonReadJsonFromURL { public static void main(String[] args) { try { /* * World time API URL from which * we are going to read and parse * JSON using Gson */ URL url = new URL("http://worldtimeapi.org/api/timezone/Asia/Kolkata"); //create a reader to read the URL InputStreamReader reader = new InputStreamReader(url.openStream()); /* * Use the fromJson method of the Gson * class that accepts a reader object */ JsonObject jsonObject = new Gson().fromJson(reader, JsonObject.class); //get the datetime property System.out.println("Current date time is: " + jsonObject.get("datetime").getAsString()); //close the reader reader.close(); }catch(Exception e) { //e.printStackTrace(); System.out.println(e); } } } |
Output
1 |
Current date time is: 2023-03-23T16:26:34.188527+05:30 |
Now, instead of converting URL content to a JsonObject object, we can also convert it to a Java POJO using the same method.
Please let me know your views in the comments section below.