simDev1234
심플하고 차분하게
simDev1234
전체 방문자
오늘
어제
  • 분류 전체보기
    • Computer Science
      • Basic Math
      • Data Structure
      • Algorithm
      • Database
      • OS
    • Language
      • Java
      • Kotlin
      • SQL
    • Framework
      • Spring
      • Orm&Mapper
      • 프로젝트로 스프링 이해하기
      • 스프링 라이브러리
    • Infra
      • Cloud
      • Docker
      • Redis
      • AWS, Azure
      • Device
    • Etc
      • CleanCoding
    • Git,Github

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • controllerTest
  • 스프링
  • 자바프로그램
  • 404
  • 참조타입
  • 자바
  • 참조변수
  • scanner #next() #nextLine()
  • 자바프로그래밍
  • 자바메모리구조
  • 컨트롤러
  • JVM메모리구조
  • null

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
simDev1234

심플하고 차분하게

Framework/스프링 라이브러리

[JSON 파싱] ObjectMapper, Simple-json

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;
}

 

 

[출처]

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

'Framework > 스프링 라이브러리' 카테고리의 다른 글

[스프링 시큐러티] JWT 토큰 + 스프링 시큐러티  (0) 2022.11.18
[Scheduler] 스케줄러 사용하기 (feat. 쓰레드, 쓰레드풀)  (0) 2022.11.11
[스프링 시큐러티] 스프링 시큐러티 자료 모음 (수정중)  (0) 2022.10.29
[TEST] TDD 방식에 대한 자료 모음 (수정중)  (0) 2022.10.28
[TEST] Controller Test에서 ObjectMapper 사용하기  (0) 2022.09.20
    'Framework/스프링 라이브러리' 카테고리의 다른 글
    • [Scheduler] 스케줄러 사용하기 (feat. 쓰레드, 쓰레드풀)
    • [스프링 시큐러티] 스프링 시큐러티 자료 모음 (수정중)
    • [TEST] TDD 방식에 대한 자료 모음 (수정중)
    • [TEST] Controller Test에서 ObjectMapper 사용하기
    simDev1234
    simDev1234
    TIL용 블로그. * 저작권 이슈가 있는 부분이 있다면 댓글 부탁드립니다.

    티스토리툴바