简体   繁体   English

如何使用Spring和Hibernate生成消耗JSON对象的JSON响应

[英]How to produce json response that consumes json object using spring and Hibernate

I am getting 415 Error. 我收到415错误。 This is my mapping used for getting the json response 这是我用于获取json响应的映射

@RequestMapping(value="/details", method= RequestMethod.POST ,
        consumes= MediaType.APPLICATION_JSON_VALUE ,
        produces= MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<UserDetails> addUserDetails(@RequestBody 
                RegisterInput registerInput)throws ValidationException{

    if(registerInput==null || registerInput.getUserName()==null){
                throw new ValidationException("Input is not valid");
    }
    UserDetails userDetails=new UserDetails(registerInput.getUserName(),
                    registerInput.getFirstName(), registerInput.getLastName(), registerInput.getPassword());
    userDetailsService.addUserDetails(userDetails);
    return new ResponseEntity<UserDetails>(userDetails, HttpStatus.OK);
}

pom.xml 的pom.xml

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.13</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.4.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.4.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.4</version>
</dependency>

Help me with how to get the json response as it says error 415 in my case. 帮助我如何获取json响应,因为在我的情况下显示错误415。 Thanks in advance 提前致谢

where UserDetails is the POJO class and RegisterInput is to store the input and return json object. 其中UserDetails是POJO类,而RegisterInput是存储输入并返回json对象。 The following is my pom. 以下是我的pom。

You can refactor your method to return the response directly to response body via @ResponseBody 您可以重构您的方法,以通过@ResponseBody将响应直接返回到响应主体

   @RequestMapping(value="/details", method= RequestMethod.POST ,
            consumes= MediaType.APPLICATION_JSON_VALUE ,
            produces= MediaType.APPLICATION_JSON_VALUE)
   @ResponseBody public UserDetails addUserDetails(@RequestBody 
                                        RegisterInput registerInput)throws ValidationException{

        if(registerInput==null || registerInput.getUserName()==null){
           throw new ValidationException("Input is not valid");
         }
         UserDetails userDetails=new userDetails(registerInput.getUserName(),
                        registerInput.getFirstName(), registerInput.getLastName(), registerInput.getPassword());
          userDetailsService.addUserDetails(userDetails);
          return userDetails;
   }

note also that you need jackson 2.x dependencies only if you're using spring 4 还要注意,仅当您使用spring 4时,才需要jackson 2.x依赖项

OR 要么

jackson 1.9.x only if your using Spring 3.xx 仅当您使用Spring 3.xx时才可使用jackson 1.9.x

You can have your controller annotated with @RestController (instead of with the classic @Controller ). 您可以使用@RestController注释控制器(而不是经典的@Controller )。

This way, you're telling Spring to use the object you are returning as your response's body. 这样,您就告诉Spring将要返回的对象用作响应的主体。

Make sure you are sending both Accept and Content-Type headers with application/json and that the Json you're sending is well-formed. 确保同时发送带有application/json AcceptContent-Type标头,并且要发送的Json格式正确。

You need make your post data to your url is json. 您需要将发布的数据设为json。 I in doubt you post data is wrong. 我怀疑您发布数据是错误的。 This post also good example Spring rest using @Controller and @ResponseBody 这篇文章也是使用@Controller和@ResponseBody的Spring rest的好例子

You can get JSON as response back via setting 您可以通过设置将JSON作为响应返回

ResponseEntity ResponseEntity

as return type of your method in controller class. 作为控制器类中方法的返回类型。 You can also add additional json key value pair via creating Map lets see the below example; 您还可以通过创建Map来添加其他json键值对,请参见以下示例;

@DeleteMapping("/delete/{id}")
public ResponseEntity<Object> deleteDepartment(@PathVariable Long id) throws NotFoundException {


    Optional<Department> department = this.departmentService.findADepartment(id);
    if (department == null)
        return ResponseEntity.status(HttpStatus.NOT_FOUND).build();

    Map<String, String> stringStringMap = new HashMap<>();
    if (departmentService.deleteADepartment(id)) {
        stringStringMap.put("status", "success");
        stringStringMap.put("message", "successfully deleted");
        stringStringMap.put("code", "200");
        return ResponseEntity.status(HttpStatus.OK).
                body(stringStringMap);

    } else {
        stringStringMap.put("status", "failed");
        stringStringMap.put("message", "not  deleted");
        stringStringMap.put("code", "404");
        return ResponseEntity.status(HttpStatus.NOT_FOUND).
                body(stringStringMap);

    }

}

Here Input URL is 这里的输入URL是

http://localhost:8080/department/delete/7

And Output Response is 输出响应是

{
"code": "200",
"message": "successfully deleted",
"status": "success"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM