简体   繁体   English

如何使用@RequestBody 或@RequestParam 接收 json object

[英]how to receive a json object with @RequestBody or @RequestParam

First of all I apologize, I am new using this technology and I really have many doubts.首先我很抱歉,我是使用这项技术的新手,我真的有很多疑问。 I am trying to send a json object to my controller class, the problem is that with @RequestBody all the data arrives but the foreign keys arrive null . I am trying to send a json object to my controller class, the problem is that with @RequestBody all the data arrives but the foreign keys arrive null . Example enter a new user with the id of a role that already exists in the BD, the user data arrives complete but the role ID arrives null示例输入一个新用户,其角色ID已经存在于BD中,用户数据到达完成但角色ID到达null

First I register the data of the role via POST and everything works perfectly with @RequestBody , but when I try to register a user with the role_id that is already saved in the database also using @RequestBody it is saved with the id_rol null首先,我通过 POST 注册角色的数据,并且一切都与@RequestBody完美配合,但是当我尝试使用已经保存在数据库中的role_id注册用户时,也使用@RequestBody它与id_rol null保存

My user entity:我的用户实体:

@Entity
public class Usuario implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String correo;
    private String pass;
    private boolean activo;

    @OneToOne(optional = false, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name="rol_id", nullable = false)
    private Rol rol;

public Usuario(){}

public Usuario(String correo, String pass, boolean activo, Rol rol) {
        this.correo = correo;
        this.pass = pass;
        this.activo = activo;
        this.rol = rol;
    }
/*getter y setter*/

My role entity:我的角色实体:

@Entity
//@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Rol implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String nombre;
    private boolean activo;

    @OneToMany(mappedBy = "rol")
    private List<Usuario> usuarios;

public Rol(){}

public Rol(String nombre, boolean activo, List<Usuario> usuarios) {
        this.nombre = nombre;
        this.activo = activo;
        this.usuarios = usuarios;
    }
/*getter y setter*/

User Repository:用户存储库:

@Repository
public interface UsuarioRepository extends JpaRepository<Usuario, Serializable> {
    public abstract Usuario findByCorreo(String correo);

}

Role Repository:角色库:

public interface RolRepository extends JpaRepository<Rol, Serializable> {
}

User controller class:用户 controller class:

@RestController
@RequestMapping("/v1")
public class UsuarioController {

    @Autowired
    UsuarioRepository usuarioRepository;

    @PostMapping("/usuario/add")
    public @ResponseBody ResponseEntity<String> crear(@Valid @RequestBody Usuario usuario) {
        try{
            usuarioRepository.save(usuario);
            return new ResponseEntity<String>("Registro Exitoso..", HttpStatus.OK);
        }catch (Exception e){
            return new ResponseEntity<String>("Ha ocurrido un Error..", HttpStatus.BAD_REQUEST);
        }
    }
}

role controller class:角色 controller class:

@RestController
@RequestMapping("/v1")
public class RolController {
    @Autowired
    RolRepository rolRepository;

    @PostMapping("/rol/add")
    public @ResponseBody ResponseEntity<String> crear(@Valid @RequestBody Rol rol) {
        try{
            rolRepository.save(rol);
            return new ResponseEntity<String>("Registro Exitoso..", HttpStatus.OK);
        }catch (Exception e){
            return new ResponseEntity<String>("Ha ocurrido un Error..", HttpStatus.BAD_REQUEST);
        }
    }

}   

This is what I send to my controller:这是我发送给我的 controller 的内容:

{
  "correo": "pepito@gmail.com",
  "pass": "1234",
  "activo": "true",
  "rol_id": "5"
}

And this is what I receive:这就是我收到的:

{
  "correo": "pepito@gmail.com",
  "pass": "1234",
  "activo": true,
  "rol_id": null
}

How should I receive this body with id_rol = 5?我应该如何接收这个 id_rol = 5 的身体? I know that I am doing something wrong in @RequestBody , I appreciate any example you can provide as I have searched and I have not found that.我知道我在@RequestBody做错了什么,我很感激你可以提供的任何例子,因为我已经搜索过,但我没有找到。 Thank you..!谢谢..!

This is because you are sending a wrong JSON structure to your REST Controller.这是因为您向 REST Controller 发送了错误的 JSON 结构。

In your Usuario class, the role_id is actually an object field with a name rol which represents Rol class.在您的Usuario中, role_id实际上是一个 object 字段,其名称为rol ,代表Rol class。 So you need to pass Rol with id as an JSON object in your request:因此,您需要在请求中将带有idRol作为 JSON object 传递:

{
  "correo": "pepito@gmail.com",
  "pass": "1234",
  "activo": "true",
  "rol": {
    "id":"5"
  }
}

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

相关问题 如何同时使用@RequestBody 和@RequestParam - How to use @RequestBody and @RequestParam together 持久化新对象的正确方法是什么? 使用@RequestBody 接收构建的json 对象还是接收许多@RequestParam? - What is the proper approach on persisting a new object? Receiving a built json object with @RequestBody or receiving many @RequestParam? Bean验证将对象RequestParam转换为@RequestBody - Bean Validation transforms Object RequestParam into @RequestBody Spring Controller无法通过RequestBody或RequestParam接收文件 - Spring Controller does not receive file through RequestBody or RequestParam 我们可以在 object 中接收@RequestParam - can we receive @RequestParam in object 如何发送请求上传文件与@RequestParam CommonsMultipartFile文件,@ RequestBody用户userDetailsId等java对象? - How to send a request upload a file with java object like @RequestParam CommonsMultipartFile file ,@RequestBody User userDetailsId? Java Spring @RequestBody-如何通过两个连接的实体接收有效的JSON - Java Spring, @RequestBody - how to receive valid JSON with two connected entities 如何为请求正文发送自定义验证Json对象? - How to send a custom validation Json object for the requestbody? @RequestBody 和 @RequestParam 的 RestTemplate - RestTemplate for @RequestBody and @RequestParam 如何将@RequestParam映射到对象? - How to map @RequestParam to object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM