Post

Object Mapper로 Json속에서 value 뽑기

Object Mapper로 Json속에서 value 뽑기

spring

간단한 entity를 만들고 Mysql과 연동하여 테스트를 했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.sung_1.back_front.dto;  
  
import jakarta.persistence.*;  
import lombok.AllArgsConstructor;  
import lombok.Getter;  
import lombok.NoArgsConstructor;  
import lombok.Setter;  
  
@Entity  
@NoArgsConstructor  
@AllArgsConstructor  
@Getter  
@Setter  
@Table(name = "user")  
public class entity {  
  @Id  
  @GeneratedValue(strategy = GenerationType.IDENTITY)  
     private int id;  
     private String name;  
}

Controller.java

1
2
3
4
5
6
7
8
9
public class Controller {  
    private final UserService userService;  
    ObjectMapper objectMapper = new ObjectMapper();  
    @PostMapping("/api/hellobody")  
    public String helloBody(@RequestBody String body){  
        System.out.println(body);  
        return "success";  
    }  
}

postman으로 request를 날려보자 img-description success을 받을 수 있지만 로그에는

1
2
3
{
    "name" : "James"
}

Json파일 그잡채로 넘어온 것을 확인할 수 있었다. 내가 원한건 value값 하나만 넘기고 싶다… 물론 Entity로 인자를 받으면 spring내부에서 자동으로 json객체를 entity객체로 mapping해준다. 물론 format을 잘 맞췄을때 이야기이다. 한번 시도해보자. 코드를 다음과 같이 수정해보자.

1
2
3
4
5
6
7
8
...
    @PostMapping("/api/hellobody")
    public String helloBody(@RequestBody entity newentity){
        System.out.println(newentity.getId() + " " + newentity.getName());
        return "success";
    }
...

한번 request를 또 날려보자 img-description 성공이다. 로그도 살펴보자.

1
5 James

잘 넘어오긴 하지만, id를 직접 넣어줘서 request를 날려야하기 때문에 불편하다. 이름만 넣어서 insert를 하고 싶다. 앞에서 json파일 그자체를 넘겨받았는데, 여기서 value값을 추출할 수는 없을까?

ObjectMapper가 답인가?

1
2
3
4
5
6
7
8
9
10
11
12
...
    ObjectMapper objectMapper = new ObjectMapper();
    @PostMapping("/api/hellojson")
    public String helloJson(@RequestBody String body) throws Exception{
        JsonNode json= objectMapper.readTree(body);
        String name = json.get("name").asText();
        System.out.println(name);
        userService.insert(name);
        return "success";
    }
...

로그를 봐보자

1
James

의도되로 value값이 James만 넘어왔다. String으로 넘어온 Json파일에서 value값을 뽑을 수가 있었다. objectMapper로 body를 읽어오고, get함수를 통해 value값을 뽑을 수가 있다! get의 매개변수로는 key값을 넣어주면 된다.

This post is licensed under CC BY 4.0 by the author.