Published 2023. 1. 11. 17:26
반응형
- API 통신과 JSON에 대해 정리
- JSON으로 형변환 하는 방법 정리
JSON 이란?
- JSON(JavaScript Object Notation)은 데이터를 저장/전송 할 때 많이 사용되는 형식
- 서버와 클라이언트 간의 통신에서 주로 많이 사용됨
- 아래와 같이 Key, Value 구조를 가짐
{
"teamName" : "Tottenham",
"league" : "Premier League",
"ranking" : 5,
"players" : [
{
"name" : "Son Heungmin",
"backNumber" : 7,
"age" : 30
},
{
"name" : "Harry Kane",
"backNumber" : 10,
"age" : 29
},
{
"name" : "Hugo Lloris",
"backNumber" : 1,
"age" : 36
}
]
}
단일 객체 송신 예제
- Player라는 단일 객체를 만들고 전송하는 예제
Player
@Data
@AllArgsConstructor
static class Player {
private String name;
private int backNumber;
private int age;
}
RestController
@GetMapping("/player")
public Player getOnePlayer() {
Player player1 = new Player("Son Heungmin", 7, 30);
return player1;
}
결과
다중 객체 송신 예제
- 여러 객체를 묶어서 보낼때는 HashMap, ArrayList 등을 사용할 수 있음
- 이 예제에서는 ArrayList를 사용해 다중 객체를 묶어 전송해 봄
RestController
@GetMapping("/players")
public ArrayList<Player> getAllPlayer() {
Player player1 = new Player("Son Heungmin", 7, 30);
Player player2 = new Player("Harry Kane", 10, 29);
Player player3 = new Player("Hugo Lloris", 1, 36);
ArrayList<Player> players = new ArrayList<>();
players.add(player1);
players.add(player2);
players.add(player3);
return players;
}
결과
ArrayList가 포함된 객체 송신 예제
- 위에서 만든 players를 FootballTeam이라는 새로운 객체에 포함시키고, FootballTeam 고유 정보 추가
FootballTeam.class
@Data
@AllArgsConstructor
static class FootballTeam {
private String teamName;
private String league;
private Integer ranking;
private ArrayList<Player> players;
}
RestController
@GetMapping("/team")
public FootballTeam getOneTeam() {
Player player1 = new Player("Son Heungmin", 7, 30);
Player player2 = new Player("Harry Kane", 10, 29);
Player player3 = new Player("Hugo Lloris", 1, 36);
ArrayList<Player> players = new ArrayList<>();
players.add(player1);
players.add(player2);
players.add(player3);
FootballTeam footballTeam = new FootballTeam("Tottenham", "Premier League", 5, players);
return footballTeam;
}
결과
단일 객체 수신 예제
RestController
@PostMapping("/player")
public String postOnePlayer(@RequestBody Player player) {
String response = String.format("<선수 정보>\n이름 : %s\n등번호 : %d\n나이 : %d",
player.getName(), player.getBackNumber(), player.getAge());
return response;
}
결과
다중 객체 수신 예제
RestController
@PostMapping("/players")
public String postPlayers(@RequestBody List<Player> players) {
String response = "<선수단 정보>\n";
int i = 1;
for (Player player : players) {
response += String.format("선수%d: 이름 : %s\t등번호 : %d\t나이 : %d\n",
i, player.getName(), player.getBackNumber(), player.getAge());
i ++;
}
return response;
}
결과
ArrayList가 포함된 객체 수신 예제
RestController
@PostMapping("/team")
public String postOneTeam(@RequestBody FootballTeam footballTeam) {
String response = String.format("<팀 정보>\n팀명 : %s\n리그 : %s\n리그 랭킹 : %d\n",
footballTeam.getTeamName(), footballTeam.getLeague(), footballTeam.getRanking());
int i = 1;
for (Player player : footballTeam.getPlayers()) {
response += String.format("선수%d: 이름 : %s\t등번호 : %d\t나이 : %d\n",
i, player.getName(), player.getBackNumber(), player.getAge());
i ++;
}
return response;
}
결과
JsonString <-> Object 변환 방법
- 입력이 Json 형태의 String으로 들어오는 상황
- ex) String("{ "name": "Son Heungmin", "backNumber": 7, "age": 30 }") => Player 객체
- Object를 Json 형태의 String으로 변환시켜야 되는 상황
- ex) Player 객체 => String ("{ "name": "Son Heungmin", "backNumber": 7, "age": 30 }")
- 이런 상황에서는 JSONParser, gson, ObjectMapper 등을 사용하여 변환 가능
- gson 사용 방식이 가장 쉬운것 같음
JSONParser 사용 예제
라이브러리 추가
implementation 'com.googlecode.json-simple:json-simple:1.1.1'
JsonString -> Player
- String -> JSONObject -> Player
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
@PostMapping("/json-parser/string-to-player")
public Player convertStringToPlayer1(@RequestBody String jsonStr) throws ParseException {
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonStr);
Player player = new Player(jsonObject.get("name").toString(),
Integer.valueOf(jsonObject.get("backNumber").toString()),
Integer.valueOf(jsonObject.get("age").toString()));
return player;
}
결과
Player -> JsonString
- Player -> JSONObject -> String
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
@PostMapping("/json-parser/player-to-string")
public String convertPlayerToString1(@RequestBody Player player) {
JSONObject jsonPlayer = new JSONObject();
jsonPlayer.put("name", player.getName());
jsonPlayer.put("backNumber", player.getBackNumber());
jsonPlayer.put("age", player.getAge());
String jsonStr = jsonPlayer.toJSONString();
return jsonStr;
}
결과
gson 사용 예제
라이브러리 추가
implementation 'com.google.code.gson:gson:2.8.6'
JsonString -> Player, FootballTeam
import com.google.gson.*;
@PostMapping("/gson/string-to-player")
public Player convertStringToPlayer2(@RequestBody String jsonStr) {
Gson gson = new Gson();
Player player = gson.fromJson(jsonStr, Player.class);
return player;
}
@PostMapping("/gson/string-to-team")
public FootballTeam convertStringToTeam2(@RequestBody String jsonStr) {
Gson gson = new Gson();
FootballTeam footballTeam = gson.fromJson(jsonStr, FootballTeam.class);
return footballTeam;
}
결과
FootballTeam -> JsonString
import com.google.gson.*;
@PostMapping("/gson/team-to-string")
public String convertTeamToString2(@RequestBody FootballTeam footballTeam) {
Gson gson = new Gson();
String jsonStr = gson.toJson(footballTeam);
return jsonStr;
}
결과
object-mapper 사용 예제
JsonString -> FootballTeam
- String -> Map -> FootballTeam
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
@PostMapping("/object-mapper/string-to-team")
public FootballTeam convertStringToTeam3(@RequestBody String jsonStr) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> footballTeamMap = objectMapper.readValue(jsonStr, new TypeReference<>(){});
FootballTeam footballTeam = new FootballTeam(
footballTeamMap.get("teamName").toString(),
footballTeamMap.get("league").toString(),
Integer.valueOf(footballTeamMap.get("ranking").toString()),
(ArrayList<Player>) footballTeamMap.get("players"));
return footballTeam;
}
결과
FootballTeam -> JsonString
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@PostMapping("/object-mapper/team-to-string")
public String convertTeamToString3(@RequestBody FootballTeam footballTeam) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = objectMapper.writeValueAsString(footballTeam);
return jsonStr;
}
결과
반응형
'Spring Boot > 문법 정리' 카테고리의 다른 글
[Spring Boot] OAuth 2.0 로그인 (구글 로그인) (3) | 2023.01.21 |
---|---|
[Spring Boot] JpaRepository를 활용한 페이징 기능 구현 + 정렬, 검색, 알림창 띄우기를 활용한 예제 (0) | 2023.01.14 |
[Spring Boot] Exception 처리 - @ExceptionHandler, @(Rest)ControllerAdvice (+ @ModelAttribute, @InitBinder) (1) | 2023.01.10 |
[Spring Boot] Exception 처리 - 에러 페이지 적용(화면), 에러 코드 적용(API) (0) | 2023.01.09 |
[Spring Boot] Front-End 없이 Jwt 화면 로그인 구현 (1) | 2023.01.07 |