XmlElement注解在Java列表属性:要注意实例化,否则从xml数据反序列化到Java对象会失败

例如,下面的代码,Java类Conditions的属性conditionList是一个列表类型。XmlRootElement注解在conditionList的get方法上(等同于注解在属性上)。需要注意该属性的实例化,如果不实例化的话,从xml数据反序列化到Java对象的时候出错。

可以在两个地方实例化:

  • 在 get方法中,首先判断conditionList是否为null,如果为null的话,则实例化:

    package com.thb.platform;

    import java.util.ArrayList;
    import java.util.List;

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

    @XmlRootElement(name = "conditions")
    @XmlType(propOrder = {"identify", "table", "conditionList", "total", "pageSize", "pageNo"})
    public class Conditions {
    ...省略
    private List<Conditions.Condition> conditionList;

    复制代码
      @XmlElement(name = "condition")
      public List<Conditions.Condition> getconditionList(){
          if (conditionList == null) {
              conditionList = new ArrayList<>();
          }
          return this.conditionList;
      }
      
      public void setCondition( List<Conditions.Condition> conditionList) {
          this.conditionList = conditionList;
      }

    ...省略

    复制代码
      @XmlType(propOrder = {"value"})
      public static class Condition {

    ...省略
    }
    }

  • 在声明属性conditionList的时候实例化:

    package com.thb.platform;

    import java.util.ArrayList;
    import java.util.List;

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

    @XmlRootElement(name = "conditions")
    @XmlType(propOrder = {"identify", "table", "conditionList", "total", "pageSize", "pageNo"})
    public class Conditions {
    ...省略

    复制代码
      private List<Conditions.Condition> conditionList = new ArrayList<>();
    
      @XmlElement(name = "condition")
      public List<Conditions.Condition> getconditionList(){
          return this.conditionList;
      }
      
      public void setCondition( List<Conditions.Condition> conditionList) {
          this.conditionList = conditionList;
      }

    ...省略

    复制代码
      @XmlType(propOrder = {"value"})
      public static class Condition {

    ...省略
    }
    }

相关推荐
朕瞧着你甚好4 小时前
技术雷达 & Java 集成评估报告 — Apache Tika 3.3.1
java·ai编程
MacroZheng5 小时前
短短几天,暴涨2.8万Star!又一款编程神器开源!
java·人工智能·后端
SamDeepThinking5 小时前
函数式编程:用BiFunction消除多类型分支的代码重复
java·后端·面试
Flittly1 天前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
小兔崽子去哪了1 天前
Java 生成二维码解决方案
java·后端
人活一口气1 天前
从JVM调优到MCP协议:Java全栈技术体系深度总结与企业级架构实践
java·spring boot
NE_STOP1 天前
Vibe Coding -- 完整项目案例实操
java
荣码1 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
SimonKing1 天前
Google第三方授权登录
java·后端·程序员
明月光8181 天前
从一行 @Builder 说起:重新拾起 Java 的 Lombok、注解与 Builder 模式
java