0

For implementing a REST API in Java, I'm using: - Jersey JAX-RS Framework - Genson parser - Tomcat8 server - Hibernate

I have this method in a service class:

@POST
@Consumes("application/json")
public Response createUser(Users user) {
    UsersDAO u = new UsersDAO();

    if(user.getLogin() == null || user.getPasswd() == null)
        return Response.status(Response.Status.BAD_REQUEST).entity("Missing information").build();
    try{
        u.addUser(user);
    }catch(HibernateException e){
        return Response.status(Response.Status.BAD_REQUEST).entity("User already exists").build();
    }
    return Response.status(Response.Status.CREATED).build();
}

The Users class:

public class Users implements Serializable {

    @Basic(optional = false)
    @Column(name = "passwd")
    private String passwd;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "iduser")
    private Integer idUser;

    @Basic(optional = false)
    @Column(name = "login")
    private String login;

    @JoinColumn(name = "idusersgroup", referencedColumnName = "idusersgroup")
    @ManyToOne(optional = true)
    private UsersGroups idUsersGroup;

    @Transient
    private int idGroup;

    .
    .
    .
}

As you can see, I created the idGroup field just to store the id of the UsersGroups object related, so if I want to add the group in the moment of the user creation, I'll just have to include its id in the JSON instead of the UsersGroups object (the relationship is optional, a user can belong to a group or not). The problem is Genson is not adding this field to the Users object when consumes the JSON:

{
"login": "admin1",
"passwd": "12345",
"idgroup": 3
} 

If I POST this JSON and then access to the user.getIdGroup(), it returns 0, so I assume that idGroup field isn't being consumed. Could the @Transient annotation has something to do with this issue? Any idea on how to solve it? If the problem is Genson and there's any solution using another JSON parser (like Jackson), I could consider a switch

Juan
  • 1,949
  • 1
  • 15
  • 22
  • 2
    I don't use Genson, but if you have verified that this is definitely a problem with Genson, why don't you format your question as such. Remove all the noise, and just create a simple standlone or even JUnit test case with just your a simple POJO and some JSON. Anything about Jersey or Hibernate is irrelevant (that is as long as you have verified that this _is_ a Genson problem - which really is not that hard to verify) – Paul Samsotha Mar 10 '17 at 13:45

1 Answers1

0

The issue is that in the json you have idgroup with lowercase while the property in the class is with upper case G. Also make sure you have getters and setters for it or configure Genson to use private properties (you can find a few examples in the docs).

BTW genson is not aware of hibernate annotations.

eugen
  • 5,856
  • 2
  • 29
  • 26