본문 바로가기
Java

java jsonObject to map (json-simple, jackson 사용)

by 무대포 개발자 2021. 1. 15.
728x90
반응형

jsonObject to map

  • jsonObject 를 map 으로 변경.
  • jsonObject 안에 jsonArray 들어있는건 고려 X
필요 라이브러리
compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.12.1'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.12.1'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.12.1'
source

package utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.json.simple.JSONObject;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Map;

@Slf4j
public class JsonUtils {

    /**
     * jsonObject --> map 으로 변경
     * JSONObject 에 JSONArray 없어야 햠.
     * @param obj
     * @return
     */
    public static Map<String, Object> getMapFromJSONObject(JSONObject obj) {
        if (ObjectUtils.isEmpty(obj)) {
            log.error("BAD REQUEST obj : {}", obj);
            throw new IllegalArgumentException(String.format("BAD REQUEST obj %s", obj));
        }

        try {
            return new ObjectMapper().readValue(obj.toJSONString(), Map.class);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    /**
     * jsonStr --> map 으로 변경
     * JSONObject 에 JSONArray 없어 햠.
     * @param str
     * @return
     */
    public static Map<String, Object> getMapFromJSONObject(String str) {
        if (StringUtils.isEmpty(str)) {
            log.error("BAD REQUEST obj : {}", str);
            throw new IllegalArgumentException(String.format("BAD REQUEST obj %s", str));
        }
        try {
            return new ObjectMapper().readValue(str, Map.class);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}






// test

package utils;

import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.Map;

import static org.hamcrest.Matchers.is;

public class JsonUtilsTest {

    private JSONObject jsonObject;

    @Before
    public void setUp() throws Exception {
        jsonObject = new JSONObject();
        jsonObject.put("key", "key test");
        jsonObject.put("value", "value test");
    }

    @Test
    public void getMapFromJsonObject_string_입력값_테스트() throws Exception {
        Map<String, Object> map = JsonUtils.getMapFromJSONObject(jsonObject.toString());
        Assert.assertThat(map.get("key"), is("key test"));
        Assert.assertThat(map.get("value"), is("value test"));
    }
}


댓글