springMVC xml与实体对象的互转

RequestMapping注解

   @PostMapping(value = "/testXmlRequest", 
     produces = "application/xml; charset=UTF-8", 
     consumes = "application/xml; charset=UTF-8")
     public UserDto testXmlRequest(@RequestBody UserDto dto){
        dto.chgName("2342424sdfsdfsdf");
        return dto;
    }

produces 设置响应的数据格式。最终httpMessageConverter根据produces的响应media-type来选择对应的转换类。
consumes 设置请求的数据格式最终httpMessageConverter根据consumes的响应media-type来选择对应的转换类。

实体类

@XmlRootElement(name = "xml")
public class UserDto {
    @XmlElement(name = "id")
    private Integer id;
    @XmlElement(name = "name")
    private String name;
    @XmlElement(name = "sex")
    private Integer sex;

    public UserDto() {
    }

    public UserDto(Integer id, String name, Integer sex) {
        this.id = id;
        this.name = name;
        this.sex = sex;
    }

    public void chgName(String name){
        this.name = name;
    }
}

javax.xml.bind.annotation.*的相关注解。会自动封装和解析。注意:对应的field不能有getter和setter,不然会报错。
因此,通常对于属性的设置,创建对应的builder类就可以了。

例子

headers:Content-Type=application/xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xml>
    <id>12131</id>
    <name>test</name>
    <sex>1</sex>
</xml>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xml>
    <id>12131</id>
    <name>2342424sdfsdfsdf</name>
    <sex>1</sex>
</xml>

转载于:https://blog.51cto.com/881206524/2119028

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值