복붙노트

[SPRING] Spring RESTful 서비스에서 커스텀 JSON 객체 생성 및 사용

SPRING

Spring RESTful 서비스에서 커스텀 JSON 객체 생성 및 사용

내가 가진 자바 객체의 JSON 표현보다 더 복잡한 일부 JSON 객체가 있습니다. 이러한 JSON 객체를 작성하는 메소드가 있으므로이를 직접 반환하고 사용하고 싶습니다. 내 JSON을 빌드하는 데 org.json 라이브러리를 사용합니다. JSON 객체를 String으로 반환하여 GET 메서드를 사용할 수 있습니다. 이것이 올바른 방법일까요?

@RequestMapping(value = "/getjson", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public String getJson() {
    JSONObject json = new JSONObject();
     JSONObject subJson = new JSONObject();
    subJson .put("key", "value");
    json.put("key", subJson);
    return json.toString();
}

이제 JSON 객체를 어떻게 소비하는지 알고 싶습니다. 문자열로 JSON 객체로 변환 하시겠습니까?

    @RequestMapping(value = "/post", method = RequestMethod.POST, produces="application/json", consumes="application/json")
    @ResponseBody
    public String post(@RequestBody String json) {
        JSONObject obj = new JSONObject(json);
        //do some things with json, put some header information in json
        return obj.toString();
    }

이게 내 문제를 해결하는 올바른 방법일까요? 나는 초보자이기 때문에 더 잘 할 수있는 일을 친절하게 지적합니다. 참고 사항 : 나는 POJO를 반환하고 싶지 않습니다.

해결법

  1. ==============================

    1.나는 잭슨 라이브러리를 사용하여 아래와 같이 할 수 있다고 생각한다.

    나는 잭슨 라이브러리를 사용하여 아래와 같이 할 수 있다고 생각한다.

    @RequestMapping(value = "/getjson", method = RequestMethod.GET, produces="application/json")
    @ResponseBody
    public String getJson() {
       //your logic
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(json);
    }
    
    @RequestMapping(value = "/post", method = RequestMethod.POST, produces="application/json", consumes="application/json")
    @ResponseBody
    public String post(@RequestBody String json) {
        POJO pj = new POJO();
        ObjectMapper mapper = new ObjectMapper();
        pj = mapper.readValue(json, POJO.class);
    
        //do some things with json, put some header information in json
        return mapper.writeValueAsString(pj);
    }
    
  2. ==============================

    2.jackson lib를 사용할 수 있습니다. jackson은 spring mvc를 사용하여 json으로 /에서 json으로 변환 할 수 있습니다.

    jackson lib를 사용할 수 있습니다. jackson은 spring mvc를 사용하여 json으로 /에서 json으로 변환 할 수 있습니다.

  3. ==============================

    3.당신이 객체 / json-json / 객체의 직렬화와 역 직렬화에 대해 걱정할 필요가 없으므로 Spring mvc와 함께 Jackson을 사용하는 것보다는 훨씬 많은 대안이 있습니다. 그러나 당신이 아직도 과정에 나가 google의 gson를 사용하고 싶으면.

    당신이 객체 / json-json / 객체의 직렬화와 역 직렬화에 대해 걱정할 필요가 없으므로 Spring mvc와 함께 Jackson을 사용하는 것보다는 훨씬 많은 대안이 있습니다. 그러나 당신이 아직도 과정에 나가 google의 gson를 사용하고 싶으면.

    http://www.javacreed.com/simple-gson-example/

  4. ==============================

    4.기본 스프링 부트 빈을 사용하여 자동 직렬화 및 비 직렬화를 사용할 수 없습니다. 결국, 이것은 Project Lombok과 Apache BeanUtils를 포함시킨 후에 저에게 잘 돌아 왔습니다. Spring은 직렬화를 자동으로 수행 할 수없는 경우 String arg 생성자를 호출합니다.

    기본 스프링 부트 빈을 사용하여 자동 직렬화 및 비 직렬화를 사용할 수 없습니다. 결국, 이것은 Project Lombok과 Apache BeanUtils를 포함시킨 후에 저에게 잘 돌아 왔습니다. Spring은 직렬화를 자동으로 수행 할 수없는 경우 String arg 생성자를 호출합니다.

    @PostMapping("/create")
    @ResponseBody
    public User createUser(HttpServletRequest request, @RequestParam("user") User u) throws IOException {
    
        LOG.info("Got user! " + u);
    
        return u;
    }
    
    
    @ToString() @Getter() @Setter() @NoArgsConstructor()
    public class User {
        private String email;
        private String bio;
        private String image;
        private String displayName;
        private String userId;
        private long lat;
        private long lng;
    
        public User(String json) throws JsonParseException, JsonMappingException, IOException, IllegalAccessException, InvocationTargetException {
            ObjectMapper om = new ObjectMapper();
            User u = om.readValue(json, User.class);
            BeanUtils.copyProperties(this, u);
        }
    }
    

    http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgi https://projectlombok.org/

  5. from https://stackoverflow.com/questions/26115076/producing-and-consuming-custom-json-objects-in-spring-restful-services by cc-by-sa and MIT license