@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使用方法(將數據映射到java對象上)

將請求的json數據映射到@RequestBody 聲明的對象上

1.請求方式如下

將id,name,age 的值映射到對象上

2.對象定義如下

屬性名稱要和json中的名稱對應上

@Getter
@Setter
@ToString
public class UserEntity {
    private Long id;
    private String name;
    private int age;
}

3.可以看到,json數據映射到UserEntity裡

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: