简体   繁体   English

使用Postman以POST方法发送嵌套的json对象到Spring REST API

[英]Sending nested json object in POST method using Postman to Spring REST API

i am trying to send nested json object in POST request to my spring REST API. 我试图在POST请求中将嵌套的json对象发送到我的spring REST API。

Object java code 对象Java代码

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 在rest控制器中发布方法代码

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

My postman screenshot 我的邮递员截图

在此处输入图片说明


It has to return status 200 ok and object i sent, but it returns 400 bad request permanently. 它必须返回状态200正常并且已发送对象,但它会永久返回400错误请求。 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. 当我发送一个字符串(我的@RequestBody也是字符串)时还可以,但是完全无法使用自定义对象。

PS i have added comma, no changes PS我添加了逗号,没有更改

You missed the "," after the id field in JSON. 您在JSON的id字段之后错过了“,”。 proper JSON is your case would be below :- 正确的JSON是您的情况如下:-

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

It's a malformed json you are sending to the server. 您正在发送到服务器的json格式错误。 You need to add comma to separate elements in json. 您需要将逗号添加到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. 另外,您需要在对象模型中添加设置器和默认构造函数以设置这些值。

As mentioned in the comment, please add the default constructor for TestModel class. 如评论中所述,请为TestModel类添加默认构造函数。 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. 作为附加步骤,如果Web服务将接受json作为输入,则add使用带有内容类型的注释作为应用程序json。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM