1

i am trying to send nested json object in POST request to my spring REST API.

Object java code

public class TestModel {
private String id;
private String name;

public TestModel(String id, String name) {
    this.id = id;
    this.name = name;
}

public String getId() {
    return id;
}

public String getName() {
    return name;
}

}


Post method code in rest controller

@RequestMapping(value = "/helloPost")
public ResponseEntity<TestModel> helloPost(@RequestBody TestModel t) {
    return new ResponseEntity<TestModel>(t, HttpStatus.OK);
}

My postman screenshot

enter image description here


It has to return status 200 ok and object i sent, but it returns 400 bad request permanently. Please, tell me what am i doing wrong. It was ok when i sent one string(my @RequestBody was string too) but completly not working with custom objects.

P.S i have added comma, no changes

5
  • In the test model, please add the default constructor and try. Also, add consumes annotation with content type value as application json. Set it in the request header as well. Commented Sep 5, 2017 at 18:05
  • thanks, it helped a lot Commented Sep 5, 2017 at 18:13
  • Problem resolved? Commented Sep 5, 2017 at 18:14
  • Please add the error you getting now. Commented Sep 5, 2017 at 18:15
  • no error, its working now, after adding default constructor Commented Sep 5, 2017 at 18:16

3 Answers 3

2

You missed the "," after the id field in JSON. proper JSON is your case would be below :-

{
"id" : "1",
"name" : "test"
}
Sign up to request clarification or add additional context in comments.

Comments

2

It's a malformed json you are sending to the server. You need to add comma to separate elements in json.

Even postman showing wrong icon at the left.

{
"id" : 1,
"name" : "test"
}

Also you need to add setters and default constructor in object model to set those values.

Comments

1

As mentioned in the comment, please add the default constructor for TestModel class. It should resolve the problem.

As an additional step, if the web service is going to accept json as input, then add consumes annotation with content type as application json.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.