无法从json字符串实例化类型的值

时间:2014-07-27 16:00:23

标签: java json jackson jax-rs

我在用户和群组之间有多对多的双向关系。

    @Entity
    @Table(name = "UserTBL")
    public class User {

    @Id
    @SequenceGenerator(name = "user_generator", sequenceName = "user_seq", allocationSize = 1, initialValue = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_generator")
    private Long id;

    private String username;

    private String password;

    @ManyToMany
    private List<Group> groups;
}


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

    @Id
    @SequenceGenerator(name = "Group_generator", sequenceName = "group_seq", allocationSize = 1, initialValue = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Group_generator")
    private Long id;

    private String name;

    private String description;

    @ManyToMany(mappedBy = "groups")
    private List<User> users;
}

我正在开发使用java jax-rs web服务的角度js应用程序,我正在使用jackson处理json绑定但是我得到了这个例外:

无法从JSON String实例化[simple type,class com.blog.models.Group]类型的值;没有单字符串构造函数/工厂方法(通过引用链:com.blog.models.User [“groups”])

这是我发送到服务器的json对象:

{  
   "groups":[  
      "{\"id\":1,\"name\":\"admin\",\"description\":null,\"users\":[]}",
      "{\"id\":2,\"name\":\"user\",\"description\":null,\"users\":[]}"
   ],
   "username":"hussien",
   "password":"ammar"
}

资源:

@Stateless
@Path("/users")
public class UserResource {

    @EJB
    private UserFacade userFacade;

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public void createUser(User user) {
        userFacade.create(user);
    }
}

1 个答案:

答案 0 :(得分:4)

在客户端看起来,您可能会对JSON对象进行两次字符串化(组)。你应该只调用一次。这就是JSON的应用方式:

{"groups":[
{"id":1,"name":"admin","description":null,"users":[]},
{"id":2,"name":"user","description":null,"users":[]}
],
"username":"hussien",
"password":"ammar"
}