Reading JSON with Java
JSON is a "fat-free alternative" of XML format, or the structured dataset format. Here is a Java code that reads JSON data supplied by a web service. Replace the URL and perhaps the API key if the site requires it, and the app will parse the JSON response.
First of all, edit your POM (pom.xml).
Here is how you can parse the JSON.
First of all, edit your POM (pom.xml).
<dependency> <groupId>com.github.cliftonlabs</groupId> <artifactId>json-simple</artifactId> <version>2.1.2</version> </dependency>
Here is how you can parse the JSON.
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; @SuppressWarnings("deprecation") public class NewsApp { public static void main(String args[]) { JSONParser parser = new JSONParser(); String urlStr="https://newsapi.org/v1/sources"; try { URL url = new URL(urlStr); try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))) { JSONObject obj = (JSONObject) parser.parse(reader); JSONArray article= (JSONArray) obj.get("sources"); for(int i=0;i<article.size();i++){ JSONObject item=(JSONObject)article.get(i); System.out.println(item.get("name")); } } } catch (Exception e) { e.printStackTrace(); } } }
Comments
Post a Comment