@RequestBody不能映射到對象的解決
更新時間:2021年10月22日 11:04:15 作者:kalibiubiubiu
這篇文章主要介紹了@RequestBody不能映射到對象的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
@RequestBody不能映射到對象
在使用@RequestBody 映射對象時總是獲取不到json穿過來的值
@RequestMapping(value = "/json")
public @ResponseBody Items json(@RequestBody Items items) {
System.out.println(items);
return items;
}

public class Items {
private Integer id;
private String name;
private Float price;
private String pic;
private Date createtime;
private String detail;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic == null ? null : pic.trim();
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail == null ? null : detail.trim();
}
@Override
public String toString() {
return "Items [id=" + id + ", name=" + name + ", price=" + price + ", pic=" + pic + ", createtime=" + createtime
+ ", detail=" + detail + "]";
}
}
解決方法
在springmvc.xml配置文件加入fastjson庫,代碼如下
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

然后問題就解決了


@RequestBody使用方法(將數(shù)據(jù)映射到java對象上)
將請求的json數(shù)據(jù)映射到@RequestBody 聲明的對象上
1.請求方式如下
將id,name,age 的值映射到對象上

2.對象定義如下
屬性名稱要和json中的名稱對應上
@Getter
@Setter
@ToString
public class UserEntity {
private Long id;
private String name;
private int age;
}
3.可以看到,json數(shù)據(jù)映射到UserEntity里

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
詳解如何使用Jersey客戶端請求Spring Boot(RESTFul)服務
本篇文章主要介紹了詳解如何使用Jersey客戶端請求Spring Boot(RESTFul)服務,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01
Flutter ListView 上拉加載更多下拉刷新功能實現(xiàn)方法
這篇文章主要介紹了Flutter ListView 上拉加載更多下拉刷新功能實現(xiàn)方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07
Spring?Boot應用程序中如何使用Keycloak詳解
這篇文章主要為大家介紹了Spring?Boot應用程序中如何使用Keycloak詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05

