0

I am trying to set up a rest endpoint with jersey. I am using an angular2 client.

the angular code looks like this:

  post() {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    this.http.post('http://localhost:8050/rest/addentity', JSON.stringify(this.getValues()), new RequestOptions({ headers: headers })).
    subscribe(data => {
                alert('ok');
          }, error => {
              console.log(JSON.stringify(error.json()));
          });

  }

The post is sent correctly and I can see in the payload that all the values are there.

However, for two values I always get null in the server. Here's the method:

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("addentity")
public void saveEntity(User user) {
    System.out.println("ADD CALLED");
    System.out.println(user.getId()); // null
    addUser(user);
}

I have no idea why. The media type is correct, I get a 204 response...

Does anybody have any ideas what I'm doing wrong?

EDIT

JSON

{"id":"1234",
"name":"john",
"age":15,
"height":"6.2"}

User

public class User implements Serializable {

    private static final long serialVersionUID = -5320367665876425279L;

    private Integer userId;
    private String name;
    private double height;
    private int age;

    public User() {
        // TODO Auto-generated constructor stub
    }

    public User(final Integer userId, final String name,
            final double height, final int age) {
        this.userId = userId;
        this.name = name;
        this.height = height;
        this.age = age;
    }

    public Integer getuserId() {
        return userId;
    }

    public void setuserId(final Integer userId) {
        this.userId = userId;
    }

    public String getname() {
        return name;
    }

    public void setname(final String name) {
        this.name = name;
    }

    public double getheight() {
        return height;
    }

    public void setheight(final double height) {
        this.height = height;
    }

    public int getage() {
        return age;
    }

    public void setage(final int age) {
        this.age = age;
    }


}

All values except height are null or 0, so only the double value is read correctly.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
user3813234
  • 1,580
  • 1
  • 29
  • 44

1 Answers1

0

Well your actual code shows many problems, from what we can state:

  • In your User class you have an attribute userId while in your JSON you don't have it, it's id instead.
  • And the getters and setters in the User class are incorrect they should have the attribute first letter in Uppercase, ie : getage() should be getAge() and setage should be setAge().

You have to fix these problems otherwise your POJO won't be correctly mapped with your JSON.

You can refer to Getters and Setters in Java convention for further reading about it.

Community
  • 1
  • 1
cнŝdk
  • 31,391
  • 7
  • 56
  • 78