Framework/스프링 라이브러리

[JSON 파싱] ObjectMapper, Simple-json

simDev1234 2022. 10. 24. 10:57

1. ObjectMapper

- Jackson 라이브러리를 활용한 것이라고 한다.

- 수업에서는 test 코드를 작성할 때 ObjectMapper를 사용했다.

https://why-dev.tistory.com/266

 

[스프링] Controller Test : Json-Path와 Jackson라이브러리

| 개요 - Controller Test에서는 URI를 통해 전송되는 HTTP 요청이 MVC 모델을 거친 후 응답하는 과정이 정상적인가를 확인한다. - 이 과정에서 스프링은 ObjectMapper를 통해 Json Object로 문자열을 파싱하는 J

why-dev.tistory.com

 

2. simple-json 사용하기

- gradle의 경우 build.gradle에 아래를 넣어준다.

implementation 'com.googlecode.json-simple:json-simple:1.1.1'

- 자바에서 제공하는 URL과 JsonParser를 사용하는 파싱 방법과 동일하나,

  자바의 JsonParser 대신 라이브러리를 사용한 것이다.

- 수업에서는 OpenAPI를 가져올 때 해당 파싱을 사용했다.

 

[ Open API 결과값 파싱하기 ]

(1) Data 가져오기 (문자열)

private String getWeatherString(){
    String apiUrl = "https://api.openweathermap.org/data/2.5/weather?q=seoul&appid=" + apiKey;

    try {

        URL url = new URL(apiUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        int responseCode = connection.getResponseCode();

        BufferedReader br;

        if (responseCode == 200) {
            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } else {
            br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        }

        String inputLine;
        StringBuilder response = new StringBuilder();

        while((inputLine = br.readLine()) != null) {
            response.append(inputLine);
        }
        br.close();

        return response.toString();

    } catch(Exception e){
        return "failed to get response";
    }
}

(2) 문자열 Data 파싱하기

private Map<String, Object> parseWeather(String jsonString){
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject;

    try {
        jsonObject = (JSONObject) jsonParser.parse(jsonString);
    } catch(ParseException e){
        throw new RuntimeException(e);
    }

    Map<String, Object> resultMap = new HashMap();

    JSONObject mainData = (JSONObject) jsonObject.get("main");
    JSONObject weatherData = (JSONObject) ((JSONArray) jsonObject.get("weather")).get(0);

    resultMap.put("temp", mainData.get("temp"));
    resultMap.put("main", weatherData.get("main"));
    resultMap.put("icon", weatherData.get("icon"));

    return resultMap;
}

 

 

[출처]

부트캠프 수업을 들은 후 정리한 내용