Spring JSON 请求正文未映射到 Java POJO

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38960117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:46:45  来源:igfitidea点击:

Spring JSON request body not mapped to Java POJO

javajsonspringspring-mvcHymanson

提问by Y. Chen

I'm using Spring to implement a RESTful web service. One of the endpoints takes in a JSON string as request body and I wish to map it to a POJO. However, it seems right now that the passed-in JSON string is not property mapped to the POJO.

我正在使用 Spring 来实现 RESTful Web 服务。其中一个端点将 JSON 字符串作为请求正文,我希望将其映射到 POJO。但是,现在似乎传入的 JSON 字符串不是映射到 POJO 的属性。

here's the @RestController interface

这是@RestController 接口

@RequestMapping(value="/send", headers="Accept=application/json", method=RequestMethod.POST)
public void sendEmails(@RequestBody CustomerInfo customerInfo);

the data model

数据模型

public class CustomerInfo {
    private String firstname;
    private String lastname; 
    public CustomerInfo() {
        this.firstname = "first";
        this.lastname = "last";
    }

    public CustomerInfo(String firstname, String lastname)
    {
        this.firstname = firstname;
        this.lastname = lastname;
    }

    public String getFirstname(){
        return firstname;
    }

    public void setFirstname(String firstname){
        this.firstname = firstname;
    }

    public String getLastname(){
        return lastname;
    }

    public void getLastname(String lastname){
        this.lastname = lastname;
    }
}

And finally my POST request:

最后我的 POST 请求:

{"CustomerInfo":{"firstname":"xyz","lastname":"XYZ"}}

with Content-Type specified to be application/json

内容类型指定为 application/json

However, when I print out the object value, the default value("first" and "last") got printed out instead of the value I passed in("xyz" and "XYZ")

但是,当我打印出对象值时,打印的是默认值(“first”和“last”)而不是我传入的值(“xyz”和“XYZ”)

Does anyone know why I am not getting the result I expected?

有谁知道为什么我没有得到预期的结果?

FIX

使固定

So it turned out that, the value of request body is not passed in because I need to have the @RequestBody annotation not only in my interface, but in the actual method implementation. Once I have that, the problem is solved.

所以事实证明,请求体的值没有传入,因为我不仅需要在我的接口中使用@RequestBody 注释,而且在实际的方法实现中也需要使用 @RequestBody 注释。一旦我有了它,问题就解决了。

采纳答案by Y. Chen

So it turned out that, the value of request body is not passed in because I need to have the @RequestBody annotation not only in my interface, but in the actual method implementation. Once I have that, the problem is solved.

所以事实证明,请求体的值没有传入,因为我不仅需要在我的接口中使用@RequestBody 注释,而且在实际的方法实现中也需要使用 @RequestBody 注释。一旦我有了它,问题就解决了。

回答by DwB

The formatting on this is terrible, but this should work for Hymanson configuration.

这个格式很糟糕,但这应该适用于Hyman逊配置。

<!-- Use Hymanson for JSON conversion (POJO to JSON outbound). -->
<bean id="jsonMessageConverter"
            class="org.springframework.http.converter.json.MappingHymanson2HttpMessageConverter"/> 

<!-- Use JSON conversion for messages -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonMessageConverter"/>
        </list>
    </property>
</bean>

ALso, as mentioned in a comment, your JSON is wrong for your object.

另外,如评论中所述,您的 JSON 对于您的对象是错误的。

{"firstname":"xyz",??"lastname":"XYZ"}

does appear to be the correct JSON for your object.

似乎是您对象的正确 JSON。

回答by sanjeevjha

You can do it in many ways, Here i am going to do it in below different ways-

您可以通过多种方式做到这一点,在这里我将通过以下不同的方式做到这一点-

NOTE:request data shuld be {"customerInfo":{"firstname":"xyz","lastname":"XYZ"}}

NOTE:请求数据应该是 {"customerInfo":{"firstname":"xyz","lastname":"XYZ"}}

1st wayWe can bind above data to the map as below

1st way我们可以将上述数据绑定到地图,如下所示

@RequestMapping(value = "/send", headers = "Accept=application/json", method = RequestMethod.POST)
public void sendEmails(@RequestBody HashMap<String, HashMap<String, String>> requestData) {

    HashMap<String, String> customerInfo = requestData.get("customerInfo");
    String firstname = customerInfo.get("firstname");
    String lastname = customerInfo.get("lastname");
    //TODO now do whatever you want to do.
}

2nd waywe can bind it directly to pojo

2nd way我们可以直接绑定到 pojo

step 1create dto class UserInfo.java

step 1创建 dto 类 UserInfo.java

public class UserInfo {
    private CustomerInfo customerInfo1;

    public CustomerInfo getCustomerInfo1() {
        return customerInfo1;
    }

    public void setCustomerInfo1(CustomerInfo customerInfo1) {
        this.customerInfo1 = customerInfo1;
    }
}

step 1.create another dto classCustomerInfo.java

step 1.创建另一个 dto 类CustomerInfo.java

class CustomerInfo {
        private String firstname;
        private String lastname;

        public String getFirstname() {
            return firstname;
        }

        public void setFirstname(String firstname) {
            this.firstname = firstname;
        }

        public String getLastname() {
            return lastname;
        }

        public void setLastname(String lastname) {
            this.lastname = lastname;
        }
    }

step 3bind request body data to pojo

step 3将请求正文数据绑定到 pojo

 @RequestMapping(value = "/send", headers = "Accept=application/json", method = RequestMethod.POST)
    public void sendEmails(@RequestBody UserInfo userInfo) {

        //TODO now do whatever want to do with dto object
    }

I hope it will be help you out. Thanks

我希望它会帮助你。谢谢

回答by Anil

remove those two statements from default constructor and try

从默认构造函数中删除这两个语句并尝试

回答by Devendra Singraul

Sample Data :

样本数据 :

[  
{  
  "targetObj":{  
     "userId":1,
     "userName":"Devendra"
  }
},
{  
  "targetObj":{  
     "userId":2,
     "userName":"Ibrahim"
  }
},
{  
  "targetObj":{  
     "userId":3,
     "userName":"Suraj"
  }
}
]

For above data this pring controller method working for me:

对于上述数据,此 pring 控制器方法对我有用:

@RequestMapping(value="/saveWorkflowUser", method = RequestMethod.POST)
public void saveWorkflowUser (@RequestBody List<HashMap<String ,HashMap<String , 
  String>>> userList )  {
    System.out.println(" in saveWorkflowUser : "+userList);
 //TODO now do whatever you want to do.
}