JSON 사용하기

hyunn·2021년 8월 9일
0

Java-basic

목록 보기
25/26
post-thumbnail

JSON

JavaScript Object Notation

속성 - 값 쌍으로 연결

전송하면서 값 변경 가능 -> 쪽지 시스템에 이용가능


IntelliJ에 GSON 추가

Gson 2.8.7

GSON - 구글사에서 배포한 JSON

build.gradle -> dependencies 추가

// https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.7'

GSON 써보기 (toJson)

객체 -> 문자열

import com.google.gson.Gson;

public class NoteTest {
    public static void main(String[] args) {
        NoteDTO dto = NoteDTO.builder().who("A").whom("B").content("밥먹자").build();

        Gson gson = new Gson();

        String jsonStr = gson.toJson(dto);

        System.out.println(jsonStr);
    }
}

출력결과

{"who":"A","whom":"B","content":"밥먹자"}

입력받은 객체를 문자열화해서 출력


GSON 역변환 (fromJson)

문자열 -> 객체

import com.google.gson.Gson;

public class NoteTest {
    public static void main(String[] args) {
        NoteDTO dto = NoteDTO.builder().who("A").whom("B").content("밥먹자").build();

        Gson gson = new Gson();

        String jsonStr = gson.toJson(dto);

        System.out.println(jsonStr);
/////////////////////////////////////////////////////////////////////
        NoteDTO result = gson.fromJson(jsonStr, NoteDTO.class);

        System.out.println(result);
    }
}

출력결과

{"who":"A","whom":"B","content":"밥먹자"}
NoteDTO(no=null, who=A, whom=B, content=밥먹자)

위에서 출력된 문자열을 아래의 객체값으로 다시 변환



Builder와 Gson 통해 map에 값 추가하기

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Command {
    private String oper;

    //객체 내에 또다른 객체를 가지는 구조
    private NoteDTO noteDTO;
}

Command는 객체 내에 또다른 객체 NoteDTO를 가지는 구조로 구성


public class NoteTest {
    public static void main(String[] args) {
        //add
        NoteDTO data = NoteDTO.builder().who("A").whom("B").content("커피한잔?").build();

        Command command = Command.builder().oper("ADD").noteDTO(data).build();

        System.out.println(command);

        Gson gson = new Gson();

        System.out.println(gson.toJson(command));
    }
}

Json은 구조화를 도와줌





Json과 Map을 이용한 쪽지함 프로그램


기초설계

추가

필요값

  • who : 누가

  • whom : 누구에게

  • content : 어떤 내용을


확인

필요값

  • whom : 누구의 쪽지함?

삭제

필요값

  • whom : 누구의 쪽지함?

  • no : 삭제할 쪽지 번호


흐름

사용자 A가 사용자 B에게 쪽지 전송

  1. 누가 "A" 2. 누구에게 "B" 3. 내용 "Hello"

전송한 쪽지가 NoteServer 쪽지서버에 도착

도착한 쪽지는 ArrayList로 정의된 쪽지함DB에 저장됨 (쪽지함 = service객체 자체)

쪽지함 DB에 저장된 쪽지는 사용자가 원할때 불러올 수 있음

NoteServer 를 경유해 쪽지목록 출력


클래스 구조

  1. DTO 정의

    NoteDTO

  2. 서비스 객체

    NoteService

  3. 테스트용

    NoteTest


변수 설계

  1. 쪽지 번호 : no
  2. 보낸 사람 : who
  3. 받은 사람 : whom
  4. 쪽지 내용 : content



클래스 설계

객체 스펙 -> Data위주? Logic위주?

NoteService -> Logic위주 클래스

= Method 정의 우선


추가 add

Integer add (NoteDTO dto) {}

return type은 총 몇회의 추가를 했는지를 반환 = Integer

그냥 int type은 초기값이 0이기때문에 null값을 주기위해 Integer 사용


목록 getList

List< NoteDTO > getList(String owner) {}

목록 전체를 반환해야하므로 리턴타입은 List

누구의 쪽지함인지 받아야하므로 파라미터는 owner로 설정

위의 설계에 따르면 owner = whom


삭제 remove

boolean ramove (Integer no) {}

삭제유무만 표현해주면 되므로 리턴타입은 boolean으로 설정


멤버변수 설정

멤버변수로 설정해야하는 값 = 누적 / 상태 / 조력자

누적값이어야하는 쪽지목록 NoteDTO, ID별 쪽지함 ArrayList


쪽지함

Map <String, ArrayList< NoteDTO >>

특정 ID의 쪽지함이어야하므로 key값은 아이디를 나타낼 String

쪽지의 전체목록을 저쟝해야하므로 value값은 ArrayList







쪽지함에 쪽지보내고 목록 불러오기

public class NoteServer {
    //bad code
    public static void main(String[] args) throws  Exception{
        NoteService service = new NoteService();

        //serversocket
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("Ready...");

        //loop
        while (true) {
            Socket socket = serverSocket.accept();
            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
            String msg = dataInputStream.readUTF();

            Gson gson = new Gson();

            Command command = gson.fromJson(msg, Command.class);  //Command type의 문자열 인스턴스로 만들어줘
            System.out.println(command);
            
            String oper = command.getOper();
            if (oper.equalsIgnoreCase("ADD")) {
                service.add(command.getNoteDTO());
            }else if (oper.equalsIgnoreCase("READ")) {
                String owner = command.getNoteDTO().getWhom();
                System.out.println(service.getList(owner));
            }
        }
    }
}

public class NoteClient {
    //bad code
    public static void main(String[] args) throws Exception{

        NoteDTO data = NoteDTO.builder().who("A").whom("B").content("커피한잔?").build();
        Command command = Command.builder().oper("add").noteDTO(data).build();
      //Command command = Command.builder().oper("read").noteDTO(data).build();

        Gson gson = new Gson();

        String str = gson.toJson(command);

        Socket socket = new Socket("192.168.0.17", 9999);
        DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());

        dataOutputStream.writeUTF(str);
    }
}

Ready...
Command(oper=ADD, noteDTO=NoteDTO(no=null, who=A, whom=B, content=커피한잔?))
Command(oper=ADD, noteDTO=NoteDTO(no=null, who=A, whom=B, content=커피한잔?))
Command(oper=ADD, noteDTO=NoteDTO(no=null, who=A, whom=B, content=커피한잔?))
Command(oper=read, noteDTO=NoteDTO(no=null, who=A, whom=B, content=커피한잔?))
[NoteDTO(no=1, who=A, whom=B, content=커피한잔?), NoteDTO(no=2, who=A, whom=B, content=커피한잔?), NoteDTO(no=3, who=A, whom=B, content=커피한잔?)]

쪽지를 보낼때는 no가 null이었는데 읽어오니까 idx 적용되서 숫자가 카운팅되는 것을 볼 수 있음

1개의 댓글

comment-user-thumbnail
2023년 1월 26일

커피 한 잔 할래요~ 커피 한 잔 할래요~~

답글 달기

관련 채용 정보