关于使用JAXB读取xml文档转换为java对象出现非法注解异常

java类如下:

import java.io.Serializable;

import javax.xml.bind.annotation.XmlElement;

import javax.xml.bind.annotation.XmlRootElement;

//该注解表示xml文档的根元素
@XmlRootElement
public class Book implements Serializable {

  private static final long serialVersionUID = 2791336442194888575L;
  // 该注解代表xml文档的element
  @XmlElement
  private Integer id;
  @XmlElement
  private String name;
  @XmlElement
  private String author;

  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;
  }

  public String getAuthor() {
    return author;
  }

  public void setAuthor(String author) {
    this.author = author;
  }

  @Override
  public String toString() {
    return "Book [id=" + id + ", name=" + name + ", author=" + author + "]";
  }
}

错误如下:

Class has two properties of the same name "author"



this problem is related to the following location:
at public java.lang.String com.yc.bean.Book.getAuthor()
at com.yc.bean.Book
this problem is related to the following location:
at private java.lang.String com.yc.bean.Book.author
at com.yc.bean.Book
Class has two properties of the same name "id"
this problem is related to the following location:
at public java.lang.Integer com.yc.bean.Book.getId()
at com.yc.bean.Book
this problem is related to the following location:
at private java.lang.Integer com.yc.bean.Book.id
at com.yc.bean.Book
Class has two properties of the same name "name"
this problem is related to the following location:
at public java.lang.String com.yc.bean.Book.getName()
at com.yc.bean.Book
this problem is related to the following location:
at private java.lang.String com.yc.bean.Book.name

at com.yc.bean.Book

原因:类中有两个相同的属性名,说明会同时访问getter方法和成员变量

解决办法:

1、在类上加上@XmlAccessorType(XmlAccessType.FIELD)注解,加上此注解那么xml的访问类型为成员变量,而不是getter/setter方法对。

注明:该注解每个非静态,非瞬时成员变量将会被自动绑定到xml文档中,除非标@XmlTransient注解。getter/setter方法只有明确标有JAXB注解才会被绑定。

2、不加@XmlAccessorType(XmlAccessType.FIELD)注解,将@XmlElement注解加到setter或者getter方法上,因为默认的访问类型为getter/setter方法对。

注明:每个public访问权限的getter/sette方法对和公有成员变量才会自动绑定,访问权限为private,protected和缺省访问权限的getter/setter方法对只有明确标有才会自动绑定。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Nick说说前后端

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值