Java – Can not instantiate value of type from json string

jacksonjavajax-rsjson

I have bidirection many to many relationship between users and groups .

    @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;
}

I am developing angular js applicaton with java jax-rs web service and I am handling json binding using jackson but i am getting this exception :

Can not instantiate value of type [simple type, class com.blog.models.Group] from JSON String; no single-String constructor/factory method (through reference chain: com.blog.models.User["groups"])

This is my json object sent to the server :

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

Resource :

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

    @EJB
    private UserFacade userFacade;

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

Best Answer

It looks like on the client side you might be stringifying your JSON object twice (the groups). You should only call this once. This is how the JSON should come over:

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