[JAVA] Json 라이브러리로 json 파싱하기 2

merci·2023년 1월 8일
0

JAVA

목록 보기
6/10

이번에는 2개의 json 파일을 연결 시켜 보려고 한다

  • 첫번째 json에는 100개의 배열 오브젝트( id는 1~100 )가 들어있다
    userId는 1~10으로 나눠서 들어있는데 이 유저아이디와 다른 json 오브젝트를 연결시키자


  • 두번째 json에는 10개의 배열 오브젝트가 들어있다.
    두번째 json 오브젝트의 id를 첫번째 json 오브젝트의 userId 와 연결 시킨다

  • 두 json 을 조합해서 만든 세번째 json 오브젝트

첫번째 포스팅과 마찬가지로 메소드는 유틸 패키지로 분리시키고 시작한다.
json 을 담을 클래스 생성은 간략하게만 소개 ( Lombok 을 이용하겠음 )

// 유틸패키지에 get메소드 분리
public class Fetch {
    public static String get(String path) {
        String download = "";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            BufferedReader br = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));

            while (true) {
                String data = br.readLine();
                if (data == null) {
                    break;
                } else {
                    download = download + data;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return download; // json 을 버퍼에 받아서 String으로 리턴

    }
}
// 첫번째 json 을 저장할 클래스
@Getter
@Setter
public class PostDto {
    private Integer userId;
    private Integer id;
    private String title;
    private String body;
}
// 두번째 json을 저장할 클래스
@ToString
@Setter
@Getter
public class UserDto {
    private Integer id;
    private String name;
    private String username;
    private String email;
    private Address address;
    private String phone;
    private String website;
    private Company company;

    @ToString
    @Setter
    @Getter
    public class Address {
        private String street;
        private String suite;
        private String city;
        private String zipcode;
        private Geo geo;

        @ToString
        @Setter
        @Getter
        public class Geo {
            private String lat;
            private String lng;
        }
    }

    @ToString
    @Setter
    @Getter
    public class Company {
        private String name;
        private String catchPhrase;
        private String bs;
    }
}
// 세번째 json을 만들 클래스 
@Getter
@Setter
public class Post {
    private Integer userId;
    private Integer id;
    private String title;
    private String body;
    private UserDto user;  // 추가될 데이터
}
// main 실행
import java.util.Arrays;
import java.util.List;

import com.google.gson.Gson;

import down.dto.Post;
import down.dto.PostDto;
import down.dto.UserDto;
import down.util.Fetch;

public class App {

    public static void main(String[] args) {
        Gson gson = new Gson();
        try {
            String str = Fetch.get("https://jsonplaceholder.typicode.com/posts");
            // Post다운
            PostDto[] post5 = gson.fromJson(str, PostDto[].class); // 원본 - 첫번째 json
            Post[] post6 = gson.fromJson(str, Post[].class); // 조합 결과
            List<PostDto> PostDlist = Arrays.asList(post5); // 다운받은 리스트
            List<Post> Postlist = Arrays.asList(post6); // 생성할 리스트 - 세번째 json

            String str1 = Fetch.get("https://jsonplaceholder.typicode.com/users");
            UserDto[] root = gson.fromJson(str1, UserDto[].class); // 두번째 json
            List<UserDto> userdto = Arrays.asList(root);
            for (int i = 0; i < Postlist.size(); i++) {
                Postlist.get(i).setUser(userdto.get(
                        (PostDlist.get(i).getUserId() - 1)));
                // 유저 아이디는 1부터 시작 인덱스에 접근하기 위해 -1
            }
            String json = gson.toJson(Postlist);
            System.out.println(json);  // json viewer 로 결과 확인
        } catch (Exception e) {
            e.getStackTrace();
        }
    }
}

조합된 결과가 나온다

profile
작은것부터

0개의 댓글