JSON in Java and Jackson Part 1 Return JSON from the server

at first

Let's look back on the handling of JSON using Jackson in Java. In the case of my project, Java is almost a Web system, and the cooperation between Servlet and JavaScript is important. First of all, I tried to return JSON from the server this time. Except for the implementation in Servlet, most of the references are diverted.

environment

Source

Java class creation for JSON

First of all, in order to convert to JSON, it is necessary to create a Java class to store the object for it. The properties of id (number type), name (string type), and datas (array) are prepared as follows. The key is the annotation by @JsonProperty. Without it, an exception will be thrown.

JsonBean.java


package servletTest;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;

public class JsonBean {

	@JsonProperty("id")
	private int id;

	@JsonProperty("name")
	private String name;

	@JsonProperty("datas")
	private List<String> datas;

	public void setId(int id) {
		this.id = id;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setDatas(List<String> datas) {
		this.datas = datas;
	}
}

Creating a Servlet

Create an object using the Java class created in the previous section, convert it to a Json string with the writeValueAsString method of the ObjectMapper class, and return it to the client.

SetvletTest.java


package servletTest;

import java.io.IOException;
import java.util.List;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


//Reference https://itsakura.com/java-jackson

@WebServlet("/helloworld")
public class ServletTest extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    	//Set a value in a Java object
    	JsonBean jsonBean = new JsonBean();
    	jsonBean.setId(1);
    	jsonBean.setName("kimisyo");
    	List<String> datas = new ArrayList<>();
    	datas.add("Programmer");
    	datas.add("Data Scientist");
    	jsonBean.setDatas(datas);

    	ObjectMapper mapper = new ObjectMapper();
    	try {
    		//Convert from Java object to JSON
    		String testJson = mapper.writeValueAsString(jsonBean);
    		//JSON output
    		response.getWriter().write(testJson);
    	} catch (JsonProcessingException e) {
    		e.printStackTrace();
    	}
    }
}

Execution result

When the above is executed in Eclipse, the following character string is displayed in the browser.

{"id":1,"name":"kimisyo","datas":["Programmer","Data Scientist"]}

in conclusion

Originally, it would be better to set Content-Type as well, but I think I will have to do it from the next time onwards, so I postponed it. From the next time onward (if any), we plan to proceed with the following subjects. -~~ Get the JSON received on the client side with JavaScript ~~ --Get JSON sent from client on server side --~~ Escape of JSON string, ~~ XSS countermeasures --Embed JSON in HTML and use it from JavaScript (Java version)

reference

-Convert JSON and Java objects with Java Jackson

Recommended Posts

JSON in Java and Jackson Part 1 Return JSON from the server
JSON in Java and Jackson Part ③ Embed JSON in HTML and use it from JavaScript
JSON with Java and Jackson Part 2 XSS measures
Convert JSON and YAML in Java (using Jackson and SnakeYAML)
Convert Java enum enums and JSON to and from Jackson
[Android development] Get an image from the server in Java and set it in ImageView! !!
Correct the character code in Java and read from the URL
Kick ShellScript on the server from Java
Get history from Zabbix server in Java
Sample code to serialize and deserialize Java Enum enums and JSON in Jackson
Parse and objectize JSON using the @JsonProperty annotation of the Java library Jackson
Regarding the transient modifier and serialization in Java
[Java] The confusing part of String and StringBuilder
Capture and save from selenium installation in Java
[Java] Output the result of ffprobe -show_streams in JSON and map it to an object with Jackson
Generate OffsetDateTime from Clock and LocalDateTime in Java
[Deep Learning from scratch] in Java 1. For the time being, differentiation and partial differentiation
Read JSON in Java
POST JSON in Java
Create JSON in Java
[Android / Java] Screen transition and return processing in fragments
Java language from the perspective of Kotlin and C #
Java classes and instances to understand in the figure
Using the database (SQL Server 2014) from a Java program 2018/01/04
Reverse Enum constants from strings and values in Java
[Java] Convert JSON to Java and Java to JSON-How to use GSON and Jackson-
Find the address class and address type from the IP address with Java
[Java] JSON communication with jackson
In Java, I want to trim multiple specified characters from only the beginning and end.
Java and Iterator Part 1 External Iterator
Implement Java Interface in JRuby class and call it from Java
What I learned in Java (Part 4) Conditional branching and repetition
Apache Hadoop and Java 9 (Part 1)
Create a method to return the tax rate in Java
[Java] [jackson] Corresponds to the trailing comma (trailing comma) when parsing JSON.
Make your own simple server in Java and understand HTTP
POST Json in Java ~ HttpURLConnection ~
Think about the differences between functions and methods (in Java)
Json serialization / deserialization in Java 1.4
Get attributes and values from an XML file in Java
Let's implement the condition that the circumference and the inside of the Ougi shape are included in Java [Part 2]
Let's implement the condition that the circumference and the inside of the Ougi shape are included in Java [Part 1]
Install the memcached plugin on MySQL and access it from Java
What I have learned in Java (Part 1) Java development flow and overview
[Java] Get the dates of the past Monday and Sunday in order
I want to return to the previous screen with kotlin and java!
From fledgling Java (3 years) to Node.js (4 years). And the impression of returning to Java
[Android] Convert Map to JSON using GSON in Kotlin and Java
[Java] How to convert from String to Path type and get the path
[Ssh server] ubuntu ssh server construction-ssh connection from inside and outside the LAN
Access the network interface in Java
Guess the character code in Java
Try implementing GraphQL server in Java
Encoding and Decoding example in Java
Specify the java location in eclipse.ini
Java arguments, return values and overloads
Unzip the zip file in Java
StringBuffer and StringBuilder Class in Java
Parsing the COTOHA API in Java
Understanding equals and hashCode in Java
Server processing with Java (Introduction part.1)