在Java代码中指定用JAXB的XmlElement注解的元素的顺序

例如,下面的类RegisterResponse 使用了XmlRootElement注解,同时也使用XmlType注解,并用XmlType注解的propOrder属性,指定了两个用XmlElement注解的元素出现的顺序,先出现flag,后出现enterpriseId(在xml中的元素名称是body):

csharp 复制代码
package com.thb.server.register;

import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlType;

/**
 * 该类映射到http响应的xml
 * @author thb
 *
 */
//使用了JAXB注解,映射到xml中的response元素
@XmlRootElement(name = "response")
@XmlType(propOrder = {"flag", "enterpriseId"})
public class RegisterResponse {
    private String flag;
    private String enterpriseId;

    public RegisterResponse() {}

    //使用了JAXB注解,映射到xml中的flag元素
    @XmlElement(name = "flag", required = true)
    public String getFlag() {
        return this.flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }

    //使用了JAXB注解,映射到xml中的body元素
    @XmlElement(name = "body", required = true)
    public String getEnterpriseId() {
        return this.enterpriseId;
    }

    public void setEnterpriseId(String enterpriseId) {
        this.enterpriseId = enterpriseId;
    }

}

生成XML schema,显示顺序是flag在前,body在后:

用Postman发送http请求,得到的响应是flag在前,body在后:

作为对比,如果上面的类不使用XmlType注解,即变为下面这样:

csharp 复制代码
@XmlRootElement(name = "response")
public class RegisterResponse {
...

生成XML schema,是body在前,flag在后:

用Postman发送http请求,得到的响应是是body在前,flag在后:

相关推荐
猫耳球团40 分钟前
IDEA与Cursor跨平台协作指南
java·ide·intellij-idea
亚历克斯神42 分钟前
Java 职业发展:2026 指南
java·spring·微服务
xuhaoyu_cpp_java1 小时前
Maven学习(二)
java·经验分享·笔记·学习·maven
西门吹-禅1 小时前
java 微服务学习笔记
java·学习·微服务
小碗羊肉1 小时前
【从零开始学Java | 第三十五篇】IO流-字节流
java·开发语言
xiaomo22492 小时前
javaee-网络原理4
java·网络
Soari2 小时前
Ziggo-CaaS-Switch软件配置: undefined reference to pthread_create
java·开发语言·fpga开发·tsn·zynq·交换机配置
云烟成雨TD2 小时前
Spring AI Alibaba 1.x 系列【13】 检查点 (Checkpoint) 机制及各类持久化实现
java·人工智能·spring
殷紫川2 小时前
深入拆解 Fork/Join 框架:核心原理、分治模型与参数调优实战
java
yaaakaaang2 小时前
十六、解释器模式
java·解释器模式