2
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Jackson】JSON⇔オブジェクト変換クラス

Last updated at Posted at 2019-01-29

はじめに

REST API で JSON を扱うのでメモ

環境

maven

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>

変換クラス

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文字列⇔オブジェクト 変換クラス.
 *
 * @param <T> 変換対象のクラス
 */
public class JsonConverter<T> {

    private ObjectMapper objectMapper;

    /**
     * コンストラクタ.
     */
    public JsonConverter() {
        this.objectMapper = new ObjectMapper();
    }

    /**
     * JSON文字列からMapオブジェクトに変換します.
     *
     * @param jsonStr JSON文字列
     * @return Mapオブジェクト
     * @throws IOException 変換に失敗した場合
     */
    public Map<String, Object> convertToMap(String jsonStr) throws IOException {
        // 引数チェック
        validateJsonStr(jsonStr);

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

    /**
     * JSON文字列から自作オブジェクトへ変換します.
     *
     * @param jsonStr JSON文字列
     * @param clz 自作クラス
     * @return 自作オブジェクト
     * @throws IOException 変換に失敗した場合
     */
    public T convertToDto(String jsonStr, Class<T> clz) throws IOException {
        // 引数チェック
        validateJsonStr(jsonStr);
        validateClass(clz);

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

    /**
     * MapオブジェクトからJSON文字列へ変換します.
     *
     * @param map Mapオブジェクト
     * @return JSON文字列
     * @throws IOException 変換に失敗した場合
     */
    public String convertToStr(Map<String, Object> map) throws IOException {
        // 引数チェック
        validateMap(map);

        return this.objectMapper.writeValueAsString(map);
    }

    /**
     * 自作オブジェクトからJSON文字列へ変換します.
     *
     * @param obj 自作オブジェクト
     * @return JSON文字列
     * @throws IOException 変換に失敗した場合
     */
    public String convertToStr(T obj) throws IOException {
        // 引数チェック
        validateObj(obj);

        return this.objectMapper.writeValueAsString(obj);
    }

    /**
     * JSON文字列のチェック.
     *
     * @param jsonStr JSON文字列
     */
    private void validateJsonStr(String jsonStr) {
        if (jsonStr == null) {
            throw new IllegalArgumentException("jsonStr is null.");
        }
        if (jsonStr.isEmpty()) {
            throw new IllegalArgumentException("jsonStr is empty.");
        }
    }

    /**
     * クラスオブジェクトのチェック.
     *
     * @param clz クラスオブジェクト
     */
    private void validateClass(Class<T> clz) {
        if (clz == null) {
            throw new IllegalArgumentException("clz is null.");
        }
    }

    /**
     * Mapオブジェクトのチェック.
     *
     * @param map Mapオブジェクト
     */
    private void validateMap(Map<String, Object> map) {
        if (map == null) {
            throw new IllegalArgumentException("map is null.");
        }
    }

    /**
     * 自作オブジェクトのチェック.
     *
     * @param obj 自作オブジェクト
     */
    private void validateObj(T obj) {
        if (obj == null) {
            throw new IllegalArgumentException("obj is null.");
        }
    }
}

以上

2
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?