Try using JSON format API in Java

Introduction

Currently I started developing with API in Java. It was my first time to use API in Java and I managed to implement it, so I will write it in a memorandum sense. First of all, I will show you the general implementation. After that, I will explain it in the following sections.

--[Connect to API URL](#Connect to API URL) -[Use BufferedReader to get response from API](# Use BufferedReader to get response from API) --[Convert JSON string to Java object using ObjectMapper](#Convert JSON string to Java object using ObjectMapper)

In that, I will look at the implementation part of each section and its explanation while looking at the references.

Get API request and response

useJson.java


public static JsonNode getResult(String urlString) {
 String result = "";
 JsonNode root = null;
 try {
	URL url = new URL(urlString);
	HttpURLConnection con = (HttpURLConnection)url.openConnection();
	con.connect(); //URL connection
	BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
	String tmp = "";
	
       while ((tmp = in.readLine()) != null) {
		result += tmp;
	}

	ObjectMapper mapper = new ObjectMapper();
	root = mapper.readTree(result);
	in.close();
	con.disconnect();
 }catch(Exception e) {
 	e.printStackTrace();
 }

 return root;
}

Connect to API URL

useJson.java


URL url = new URL(urlString): //Specify API URL including request parameters
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.connect(); //Connect to URL

URL class

Specify a String type character string as an argument. Pointer a String type character string to the Web. Reference: Class URL

What is a pointer?

A pointer is a reference (pointer) to an object when it can be accessed with some logical location information.

The logical location information referred to here refers to a location (URL) on the Web.

[Reference: Pointer (Programming)](https://ja.wikipedia.org/wiki/%E3%83%9D%E3%82%A4%E3%83%B3%E3%82%BF_(%E3%83) % 97% E3% 83% AD% E3% 82% B0% E3% 83% A9% E3% 83% 9F% E3% 83% B3% E3% 82% B0))

What is logical?

"Logical" is the state of thinking in a proper way. The meanings of "theory" and "reason" are common to "line". In addition, "theory" also means "discuss", and "reason" also means "words and principles".

In other words, here it is to make a way to the URL (specify the address).

Reference: What does "logical" mean? Introducing the difference from the synonym "theoretical" and the antonyms What is the meaning of "logical"?

URLConnection class

Allow both reading and writing of resources referenced in URLs

openConnection Manipulate parameters that affect connections to remote resources Reference: Class URLConnection

Use BufferedReader to get response from API

useJson continued.java


String result = "";
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))); //Receive response
String tmp = "";
while ((tmp = in.readLine) != null){
 result += tmp;
}

BufferedReader class

Efficiently read text from a character input stream by buffering characters, arrays, and lines.

Here, it means to read JSON format text efficiently. Reference: Class BufferedReader

What is buffering?

Buffering is when exchanging data between multiple devices and software, compensating for differences in processing speed and transfer speed, and temporarily sending and receiving data to a dedicated storage area in case of communication deceleration or interruption. Save it in.

In other words, save some data at the beginning of connecting to the API with the request, and when it has accumulated to some extent, read the response safely and speed up the processing speed. Reference: Buffering [buffering] Buffering

InputStreamReader class

InputStreamReader acts as a bridge from the byte stream to the character stream

Here, it means to drop the JSON format response into the character stream. Reference: Class InputStreamReader

(HttpURLConnection)con.getInputStream

Returns an input stream that receives input from this connection. When reading from the returned input stream, a SocketTimeoutException is thrown if the read timeout expires before the data becomes readable.

"This connection" is a JSON response. Reference: getInputStream

in.readLine()

Read a line of text.

Read the response line by line [Reference: Summary of class BufferedReader method readLine ()] (https://docs.oracle.com/javase/jp/8/docs/api/java/io/BufferedReader.html)

Convert JSON string to Java object using ObjectMapper

useJson continued ②.java


JsonNode jsonResult = null; //Initialization
ObjectMapper mapper = new ObjectMapper();
jsonResult = mapper.readTree(result);

in.close();
con.disconnect();

ObjectMapper class

Can convert between Java objects and JSON strings.

Reference: Jackson usage memo JSON string → Java object Description

mapper.readTree(result)

Then, ObjectMapper.readTree reads the root node when the JSON file data is made into tree structure data as a JsonNode type object. Reference: Read data with JSON library Jackson for Java

What is tree structure data?

A tree structure is one of the data structures, and one element (node) has multiple child elements, and one child element has multiple grandchild elements. The deeper the hierarchy, the more branched. The structure. It is called this because it resembles a tree branching from trunk to branch and from branch to leaf.

The elements that make up the tree structure are called nodes, and the nodes have a parent-child relationship. A node without a parent is called a root node, and a node without a child is called a leaf node.

image.png

[Reference: Tree structure] Tree structure ](http://e-words.jp/w/%E6%9C%A8%E6%A7%8B%E9%80%A0.html)

In other words, it is readTree that plays the role of acquiring the data (root node) at the top of the tree structure.

in.close(); End of BufferedReader class

con.disconnect(); Termination (disconnection) of URL connection

At the end

I'm tired ... w I think it looks like this when connecting to a Json format API. By the way, if you handle Json in Java, you will need to include some libraries, but I think there are some that are unnecessary, so I will add them as soon as I understand. The following are currently included.

If you have any suggestions or questions in this article, I would appreciate it if you could comment.

Recommended Posts

Try using JSON format API in Java
Try using RocksDB in Java
Try using GCP's Cloud Vision API in Java
Try using the COTOHA API parsing in Java
I tried using Elasticsearch API in Java
Read JSON in Java
Format XML in Java
Zabbix API in Java
POST JSON in Java
Create JSON in Java
◆ Try calling SpringBoot + gradle REST + JSON format API
ChatWork4j for using the ChatWork API in Java
[Java] API creation using Jerjey (Jax-rs) in eclipse
Try using Sourcetrail (win version) in Java code
Try using Sourcetrail (macOS version) in Java code
Convert JSON and YAML in Java (using Jackson and SnakeYAML)
Try scraping using java [Notes]
Try calling JavaScript in Java
I tried using Google Cloud Vision API in Java
Try developing Spresense in Java (1)
Try functional type in Java! ①
Java Stream API in 5 minutes
POST Json in Java ~ HttpURLConnection ~
Try global hooking in Java using the JNativeHook library
Json serialization / deserialization in Java 1.4
Try using gRPC in Ruby
Log output in Json format using lograge / lograge-sql with RubyOnRails
Authenticate 3 or more parameters in JSON format using Spring Security
[Java] "T" is included in date type JSON in API response
[Java] Try editing the elements of the Json string using the library
Elasticsearch Operation via REST API using Apache HttpClient in Java
Translate using Microsoft Translator Text API in Java (Japanese → English)
Tips for using Salesforce SOAP and Bulk API in Java
Try implementing GraphQL server in Java
Export issues using JIRA's Java API
Encrypt using RSA cryptography in Java
Try running Selenuim 3.141.59 in eclipse (java)
Try using Redis with Java (jar)
Generate CloudStack API URL in Java
Try an If expression in Java
Hit Zaim's API (OAuth 1.0) in Java
I tried using Java8 Stream API
Parsing the COTOHA API in Java
[Java] Try to implement using generics
HTTPS connection using tls1.2 in Java 6
I tried using JWT in Java
Try running AWS X-Ray in Java
Try to implement Yubaba in Java
Try using IBM Java method tracing
JPA (Java Persistence API) in Eclipse
Try using Hyperledger Iroha's Java SDK
[Java] Where did you try using java?
Try passing values from Java Servlet to iPhone app using JSON
[Android] Convert Map to JSON using GSON in Kotlin and Java
Try using Java framework Nablarch [Web application]
Implement API Gateway Lambda Authorizer in Java Lambda
Try to solve Project Euler in Java
Data processing using stream API from Java 8
Studying Java 8 (date API in java.time package)
Try to implement n-ary addition in Java
Call the Windows Notification API in Java