프로젝트

[Project]Spring React 통신 간 JSON 파싱

째로스 2023. 7. 27. 15:35

Maven 설정

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

(https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple)

 

React에서 JSON 전송

<Button variant="primary"
    onClick={()=>{
      axios(
        {
          url: '/login',
          method: 'post',
          data: [
            {email:'test@naver.com',aaa:'aaa222'},
            {email:'test2@naver.com',aaa:'aaa333'}], 
          baseURL: 'http://localhost:8080',
          //withCredentials: true,
        }
      ).then(function (response) {
        console.log(response)
        console.log(response.data.id)
      });
}}>Login</Button>{' '}

Spring에 JSON 객체가 하나만 왔을 경우(JSONObject)

{email:'test@naver.com',aaa:'aaa222'}

 

@PostMapping(value = "/login", consumes="application/json;")
public String signIn(@RequestBody HashMap<String, Object> map){
    Object obj = parser.parse(map); 
    JSONObject jsonObj = (JSONObject)obj;
    System.out.println((String)jsonObj.get("eamil"));

	return (String)jsonObj.get("eamil");
}

 

Spring에 JSON 객체가 여러개 왔을 경우

[{email:'test@naver.com',aaa:'aaa222'},{email:'test2@naver.com',aaa:'aaa333'}]

@PostMapping(value = "/login", consumes="application/json;")
public TestDto signIn(@RequestBody List<HashMap<String, Object>> map){
    System.out.println(map);
    for(int i=0;i<map.size();++i){
        System.out.println(map.get(i));
        JSONObject jsonObj = new JSONObject(map.get(i));
        System.out.println("email="+(String)jsonObj.get("email"));
    }
    TestDto testDto =new TestDto("park","1234");
    return testDto;
}

dto는의미없는 값으로 의미없다.