springboot 接口接收及响应xml数据

1.实体类

java 复制代码
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD) // 指示JAXB直接访问类的字段而不是getter/setter方法
public class User {
    @XmlElement // 表示这个字段应该被映射为XML的一个元素
    private String name;

    @XmlElement // 表示这个字段应该被映射为XML的一个元素
    private int age;

    // 构造方法、getter和setter省略

    public User() {}

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter 和 Setter
    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

2.接口

java 复制代码
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

	//consumes 将接收到的xml数据自动转为user对象,produces 将返回user对象自动转为xml数据返回
    @PostMapping(value = "/user", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE)
    public User createUser(@RequestBody User user) {
        // 在这里可以添加处理逻辑,例如保存到数据库
        // 这里只是简单返回接收到的用户对象
        user.setAge(102);
        return user;
    }
}

3.测试

设置Content-Type

设置raw 为xml

相关推荐
卷无止境1 小时前
当FastAPI项目开始"膨胀",代码该往哪儿放
后端·python
fliter1 小时前
程序员每天能省 1 小时的 50 个 macOS/终端/Git/浏览器技巧
后端
神奇小汤圆1 小时前
Redis为什么使用哈希槽而不用一致性哈希
后端
用户8356290780511 小时前
Python设置PowerPoint幻灯片背景的方法
后端·python
站大爷IP2 小时前
Python 的 is 把我坑惨了,原来 == 和 is 在小整数池外完全是两码事
后端
用户40966601317512 小时前
Jackson 序列化:@JsonIgnore / @JsonProperty / @JsonFormat / @JsonInclude / @JsonUnwrapped 一次讲清楚
java·后端
雨落倾城夏未凉2 小时前
halcon核心-图像预处理(四)
后端
用户233376852182 小时前
一张损坏JPEG文件的背后排查
后端
nnerddboy2 小时前
Rust教程06:ESP32-rust环境搭建
开发语言·后端·rust
步行cgn2 小时前
MyBatis resultMap 结果映射完全指南
后端