Issue
I am trying to get an element from a JSON URL, but nothing seem to work. I tried to create an object to store the response, and then access it. It didn't work. Here is my code:
public class JavaApplication4 {
public static void main(String[] args) {
try {
URL url = new URL("https://jsonplaceholder.typicode.com/todos/1");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is the output from running that code:
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
I want to get the individual key values. For example, I want to get the value of "title".
Solution
There are several third-party tools to do what you want, but you can also use Java EE's Java API for JSON Processing (sometimes confusingly known as JSON-P) to process a URL's JSON data, without knowing the structure of that data.
Here's the code, which uses the code in the OP as a starting point:
package com.unthreading;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import javax.json.Json;
import javax.json.stream.JsonParser;
public class App {
public static void main(String[] args) throws IOException {
StringBuilder jsonData = new StringBuilder();
URL url = new URL("https://jsonplaceholder.typicode.com/todos/1");
try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));) {
String line;
while ((line = br.readLine()) != null) {
jsonData.append(line);
}
}
new App().processUnknownJson(jsonData.toString());
}
private void processUnknownJson(String jsonData) {
System.out.println("jsonData:" + jsonData);
JsonParser parser = Json.createParser(new StringReader(jsonData));
while (parser.hasNext()) {
JsonParser.Event event = parser.next();
switch (event) {
case START_ARRAY:
case END_ARRAY:
case START_OBJECT:
case END_OBJECT:
case VALUE_FALSE:
case VALUE_NULL:
case VALUE_TRUE:
System.out.println(event.toString());
break;
case KEY_NAME:
System.out.print(event.toString() + " " + parser.getString() + " - ");
break;
case VALUE_STRING:
case VALUE_NUMBER:
System.out.println(event.toString() + " " + parser.getString());
break;
default:
System.out.println("Unexpected event: " + event.toString());
}
}
}
}
This is the output, showing the JSON string returned from the URL, and the results from parsing that string into key/value pairs:
jsonData:{ "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}
START_OBJECT
KEY_NAME userId - VALUE_NUMBER 1
KEY_NAME id - VALUE_NUMBER 1
KEY_NAME title - VALUE_STRING delectus aut autem
KEY_NAME completed - VALUE_FALSE
END_OBJECT
The parsing code is taken from an Oracle example: Reading JSON Data Using a Parser.
I created the application as a simple Maven project using this pom.xml
:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.unthreading</groupId>
<artifactId>myjsonparser</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>myjsonparser</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.json/javax.json-api -->
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1.4</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>[1.1.2,)</version>
</dependency>
</dependencies>
</project>
Answered By - skomisa
Answer Checked By - Candace Johnson (JavaFixing Volunteer)