Java

자바 Json Parser

NaHyungMin 2021. 2. 22. 12:11

Json으로 정보 처리 하려고 만듬.

Gson만 써도 되는데.. 만든지 3달정도 되서 아래 Jackson은 확인은 해봐야 함.

사용하시려면 Jackson은 제거하고 사용하거나 확인은 해보는걸 추천. convertToClass(String value) 이 함수.

 

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.6</version>
</dependency>
<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20201115</version>
</dependency>

 

import com.google.gson.*;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

public class JsonConverter {
    private static final Gson gson = new GsonBuilder()
            .disableHtmlEscaping()
            .setPrettyPrinting()
            .serializeNulls()
            .excludeFieldsWithoutExposeAnnotation()
            .serializeSpecialFloatingPointValues()
            .create();

    public static <T extends Map<?, ?>> String convert(T obj) {
        return gson.toJson(obj);
    }

    public static <T extends Class<?>, V> String convert(T cls, V obj) {
        return gson.toJson(obj);
    }

    public static <T, V extends String> List<T> convertToClassList(Class<T> cls, V value) {
        return gson.fromJson(value, com.google.gson.reflect.TypeToken.getParameterized(List.class, cls).getType());
    }

    public static <T, V extends String> T convertToClass(Class<T> cls, V value) throws JsonSyntaxException {
        return gson.fromJson(value, (Type)cls);
    }

    public static Map<String, String> convertToClass(String value) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(value, Map.class);
    }
}

 

사용법

String jsonParameter = JsonConverter.convert(Dto.class, sendJsonDto);

ResultDto list = JsonConverter.convertToClass(ResultDto.class, jsonResult);

List<Dto> DtoList = JsonConverter.convertToClassList(Dto.class, splitText);