[JAVA] [Jackson] JSON ⇔ object conversion class

Introduction

Note that JSON is handled by REST API

environment

maven

full 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>trial</groupId>
	<artifactId>trial-json</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>trial-json</name>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
		<maven.compiler.target>${java.version}</maven.compiler.target>
		<maven.compiler.source>${java.version}</maven.compiler.source>
	</properties>

	<dependencies>
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.9.8</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.4</version>
			<scope>provided</scope>
		</dependency>

		<!-- https://mvnrepository.com/artifact/junit/junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.0</version>
				<configuration>
					<verbose>true</verbose>
					<source>${java.version}</source>
					<target>${java.version}</target>
					<encoding>${project.build.sourceEncoding}</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Conversion class

package trial.json;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

/**
 *JSON string ⇔ object conversion class.
 *
 * @param <T>Class to be converted
 */
public class JsonConverter<T> {

    private ObjectMapper objectMapper;

    /**
     *constructor.
     */
    public JsonConverter() {
        this.objectMapper = new ObjectMapper();
    }

    /**
     *Convert from JSON string to Map object.
     *
     * @param jsonStr JSON string
     * @return Map object
     * @throws IOException If conversion fails
     */
    public Map<String, Object> convertToMap(String jsonStr) throws IOException {
        //Argument check
        validateJsonStr(jsonStr);

        return this.objectMapper.readValue(jsonStr, new TypeReference<Map<String, Object>>() {});
    }

    /**
     *Convert from JSON string to self-made object.
     *
     * @param jsonStr JSON string
     * @param clz Homebrew class
     * @return Self-made object
     * @throws IOException If conversion fails
     */
    public T convertToDto(String jsonStr, Class<T> clz) throws IOException {
        //Argument check
        validateJsonStr(jsonStr);
        validateClass(clz);

        return this.objectMapper.readValue(jsonStr, clz);
    }

    /**
     *Convert from Map object to JSON string.
     *
     * @param map Map object
     * @return JSON string
     * @throws IOException If conversion fails
     */
    public String convertToStr(Map<String, Object> map) throws IOException {
        //Argument check
        validateMap(map);

        return this.objectMapper.writeValueAsString(map);
    }

    /**
     *Convert from self-made object to JSON string.
     *
     * @param obj Self-made object
     * @return JSON string
     * @throws IOException If conversion fails
     */
    public String convertToStr(T obj) throws IOException {
        //Argument check
        validateObj(obj);

        return this.objectMapper.writeValueAsString(obj);
    }

    /**
     *JSON string check.
     *
     * @param jsonStr JSON string
     */
    private void validateJsonStr(String jsonStr) {
        if (jsonStr == null) {
            throw new IllegalArgumentException("jsonStr is null.");
        }
        if (jsonStr.isEmpty()) {
            throw new IllegalArgumentException("jsonStr is empty.");
        }
    }

    /**
     *Checking class objects.
     *
     * @param clz class object
     */
    private void validateClass(Class<T> clz) {
        if (clz == null) {
            throw new IllegalArgumentException("clz is null.");
        }
    }

    /**
     *Check Map object.
     *
     * @param map Map object
     */
    private void validateMap(Map<String, Object> map) {
        if (map == null) {
            throw new IllegalArgumentException("map is null.");
        }
    }

    /**
     *Check your own objects.
     *
     * @param obj Self-made object
     */
    private void validateObj(T obj) {
        if (obj == null) {
            throw new IllegalArgumentException("obj is null.");
        }
    }
}

that's all

Recommended Posts

[Jackson] JSON ⇔ object conversion class
[Java] Object class
Moshi ~ Json conversion library ~
[Java] JSON communication with jackson
Convert ruby object to JSON format