JSON / POST API
12 Oct 2021 -
1 minute read
JSON
-
JSON : JavaScript Object Notation
-
λ€νΈμν¬λ₯Ό ν΅ν΄ λ°μ΄ν°λ₯Ό μ£Όκ³ λ°λ λ°μ΄ν° νμ
-
key(name) - value ν μ
{ "key : name" }
-
string / number / boolean / objecet : { } / array : [ ]
-
ex)
{ //string "phone_number" : "010-1234-5678", //number "age" : 10, //boolean "isAgree" : false, //object "account" : { "email" : "1234@gmail.com", "password" : "abcd1234" } } //user μ‘°ν νλ κ²½μ° //array { "user_list" : [ { "account" : "abcd", "password: "1234" }, { "account" : "aabb", "password: "1212" }, ] }
POST API
package com.example.post_api;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/api")
public class PostApiController {
@PostMapping("/post")
public void post(@RequestBody Map<String, Object> requestData){
// postλ‘ λ€μ΄μ€λ json λ°μ΄ν°λ₯Ό 맀ννκΈ° μν΄μλ @RequestBody κΌ μ μ΄μ€μΌν¨!
requestData.forEach((key, value) -> {
System.out.println("key : " + key);
System.out.println("value : " + value);
});
}
}
μ½λλ₯Ό μμ±νκ³ λ°μ΄ν°λ₯Ό μ μ‘νλ©΄
μμ κ°μ΄ λμ€λ κ±Έ λ³Ό μ μλ€
-
PostRequestDto.java
package com.example.post_api; public class PostRequestDto { private String account; private String email; private String password; // μμ²νλ jsonμ ν€μ ν΄λΉλλ κ°μ΄ 맀μΉλμ΄μΌ ν¨ public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "PostRequestDto{" + "account='" + account + '\'' + ", email='" + email + '\'' + ", password='" + password + '\'' + '}'; } }
-
PostApiController.java
package com.example.post_api; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class PostApiController { @PostMapping("/post") public void post(@RequestBody PostRequestDto requestData){ System.out.println(requestData); } }
μμ κ°μ λ°©μμ μ΄μ©ν΄
requestData.getAccount(); requestData.getEmail();
μ κ°μ΄ μΆλ ₯νλ©΄ νΉμ λ³μμ μλ λ°μ΄ν°λ₯Ό κ°μ Έμ¬ μ μλ€
@JsonProperty()
-
JSONμ ν€μ μ΄λ¦κ³Ό μλ° νμΌμμμ λ³μλͺ μ΄ λ€λ₯Ό λ? ->
@JsonProperty()
import com.fasterxml.jackson.annotation.JsonProperty; @JsonProperty("phone_number") private String phoneNumber;
-> νΉμ μ΄λ¦μ λν 맀ν κ°λ₯