java父类序列化_java-序列化为XML时忽略父类

怎么样?

家长班

我们将使用XmlAccessType.NONE告诉JAXB仅映射了显式注释的字段/属性.

import javax.xml.bind.annotation.XmlAccessType;

import javax.xml.bind.annotation.XmlAccessorType;

@XmlAccessorType(XmlAccessType.NONE)

public class Parent {

private String parentProperty1;

private String parentProperty2;

public String getParentProperty1() {

return parentProperty1;

}

public void setParentProperty1(String parentProperty1) {

this.parentProperty1 = parentProperty1;

}

public String getParentProperty2() {

return parentProperty2;

}

public void setParentProperty2(String parentProperty2) {

this.parentProperty2 = parentProperty2;

}

}

儿童班

我们将在子级上使用XmlAccessType.PROPERTY.我们要包括的父类中的任何属性都将被覆盖并显式注释.在此示例中,我们将从Parent类中引入parentProperty2.您只需要覆盖父类中的getter.

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.PROPERTY)

public class Child extends Parent {

private String childProperty;

@Override

@XmlElement

public String getParentProperty2() {

return super.getParentProperty2();

}

public String getChildProperty() {

return childProperty;

}

public void setChildProperty(String childProperty) {

this.childProperty = childProperty;

}

}

示范课

import javax.xml.bind.JAXBContext;

import javax.xml.bind.Marshaller;

public class Demo {

public static void main(String[] args) throws Exception {

JAXBContext jc = JAXBContext.newInstance(Child.class);

Child child = new Child();

child.setParentProperty1("parentProperty1");

child.setParentProperty2("parentProperty2");

child.setChildProperty("childProperty");

Marshaller marshaller = jc.createMarshaller();

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

marshaller.marshal(child, System.out);

}

}

输出量

childProperty

parentProperty2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值