2017-03-06 36 views
0

我的代码有问题...Spring Boot JSON多对一

我使用Spring Boot和Angularjs创建了我的单页应用程序。

这里是我的用户等级:

@Entity 
@Table(name = "admins") 
public class Admin { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Integer adminid; 
    private String name; 
    private String surname; 
    private String email; 
    private String login; 
    private String password; 

    @ManyToOne 
    @JoinColumn(name = "groupid") 
    private Group groupid; 
    private Boolean active; 
    @Temporal(TemporalType.TIMESTAMP) 
    private Date modifydate; 
    @Temporal(TemporalType.TIMESTAMP) 
    private Date createdate; 

    public Admin() { 
    } 
    //setters ang getters 
    } 

而且我SECEND实体类看起来

@Entity 
@Table(name = "groups") 
public class Group { 

@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
private Integer groupid; 
private String groupname; 
@Temporal(TemporalType.TIMESTAMP) 
private Date modifydate; 
@Temporal(TemporalType.TIMESTAMP) 
private Date createdate; 

@OneToMany(fetch = FetchType.EAGER, mappedBy = "groupid") 
@JsonIgnore 
private List<Admin> groupusers; 

public Group() { 
} 

public Group(Integer groupid) { 
    this.groupid = groupid; 
} 
} 

我的前端应用程序发送请求到服务器,这样

{adminid: null, name: "dsa", surname: "dsa", email: "d", login: "sada", groupid: "1", active: true} 

我有问题与群组属性,当我尝试添加新的管理员...

WARN 27742 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not construct instance of com.patryk.model.Group: no String-argument constructor/factory method to deserialize from String value ('1') 
    at [Source: [email protected]; line: 1, column: 83] (through reference chain: com.patryk.model.Admin["groupid"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.patryk.model.Group: no String-argument constructor/factory method to deserialize from String value ('1') 
    at [Source: [email protected]; line: 1, column: 83] (through reference chain: com.patryk.model.Admin["groupid"]) 

我的控制器:

@RestController 
@RequestMapping("/api/admins") 
public class AdminController { 

@Autowired 
private AdminService adminService; 


@RequestMapping(method = RequestMethod.POST) 
public ResponseEntity<?> addUser(@RequestBody Admin admin) 
{ 
    adminService.save(admin); 
    return new ResponseEntity<Admin> (admin,HttpStatus.OK); 
} 
} 

我怎样才能找到一个解决办法?任何人都知道我做错了什么?

回答

0

您必须从groupid构造对象。

{ 
    adminid: null, 
    name: "dsa", 
    surname: "dsa", 
    email: "d", 
    login: "sada", 
    groupid: { "groupid": "1"}, 
    active: true 
} 

如果你想保留一个不工作你原来的JSON,你需要创建一个自定义解串器,使您可以转换"groupid": "1"Group实体。