JavaScript Object Notation
속성 - 값 쌍으로 연결
전송하면서 값 변경 가능 -> 쪽지 시스템에 이용가능
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'
객체 -> 문자열
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":"밥먹자"}
입력받은 객체를 문자열화해서 출력
문자열 -> 객체
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=밥먹자)
위에서 출력된 문자열을 아래의 객체값으로 다시 변환
@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은 구조화를 도와줌
필요값
who : 누가
whom : 누구에게
content : 어떤 내용을
필요값
필요값
whom : 누구의 쪽지함?
no : 삭제할 쪽지 번호
사용자 A가 사용자 B에게 쪽지 전송
전송한 쪽지가 NoteServer 쪽지서버에 도착
도착한 쪽지는 ArrayList로 정의된 쪽지함DB에 저장됨 (쪽지함 = service객체 자체)
쪽지함 DB에 저장된 쪽지는 사용자가 원할때 불러올 수 있음
NoteServer 를 경유해 쪽지목록 출력
DTO 정의
NoteDTO
서비스 객체
NoteService
테스트용
NoteTest
객체 스펙 -> Data위주? Logic위주?
NoteService -> Logic위주 클래스
= Method 정의 우선
Integer add (NoteDTO dto) {}
return type은 총 몇회의 추가를 했는지를 반환 = Integer
그냥 int type은 초기값이 0이기때문에 null값을 주기위해 Integer 사용
List< NoteDTO > getList(String owner) {}
목록 전체를 반환해야하므로 리턴타입은 List
누구의 쪽지함인지 받아야하므로 파라미터는 owner로 설정
위의 설계에 따르면 owner = whom
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 적용되서 숫자가 카운팅되는 것을 볼 수 있음
커피 한 잔 할래요~ 커피 한 잔 할래요~~