Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 选择要序列化的属性_Java_Xml_Xml Serialization - Fatal编程技术网

Java 选择要序列化的属性

Java 选择要序列化的属性,java,xml,xml-serialization,Java,Xml,Xml Serialization,在我的程序中,我需要用XML存储对象。但我不希望所有属性都序列化为xml。我该怎么做 public class Car implements ICar{ //all variables has their own setters and getters private String manufacturer; private String plate; private DateTime dateOfManufacture; private int mileage; private int own

在我的程序中,我需要用XML存储对象。但我不希望所有属性都序列化为xml。我该怎么做

public class Car implements ICar{
//all variables has their own setters and getters
private String manufacturer;
private String plate;
private DateTime dateOfManufacture;
private int mileage;
private int ownerId;
private Owner owner; // will not be serialized to xml
.....
}


//code for serialize to xml
public static String serialize(Object obj)
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(baos);
    encoder.writeObject(obj);
    encoder.close();        
    return baos.toString();
}
退房。下面是一个更新的示例

BeanInfo info = Introspector.getBeanInfo(Car.class);
PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; ++i) {
    PropertyDescriptor pd = propertyDescriptors[i];
    if (pd.getName().equals("dateOfManufacture")) {
        pd.setValue("transient", Boolean.TRUE);
    }
}
BeanInfo info=Introspector.getBeanInfo(Car.class);
PropertyDescriptor[]propertyDescriptors=info.getPropertyDescriptors();
对于(int i=0;i
我选择使用带有注释的JAXB序列化。这是最好、最简单的选择。谢谢大家的帮助

public static String serialize(Object obj) throws JAXBException
{
    StringWriter writer = new StringWriter();
    JAXBContext context = JAXBContext.newInstance(obj.getClass());
    Marshaller m = context.createMarshaller();

    m.marshal(obj, writer);
    return writer.toString();
}

public static Object deserialize(String xml, Object obj) throws JAXBException
{
    StringBuffer xmlStr = new StringBuffer(xml);
    JAXBContext context = JAXBContext.newInstance(obj.getClass());
    Unmarshaller um = context.createUnmarshaller();

    return um.unmarshal(new StreamSource(new StringReader(xmlStr.toString())));
}

这是否适用于XmlEncoder的序列化,因为这是原始海报所使用的?@zdarsky.peter:看看如何将JavaBean属性标记为瞬态。或者使用JAXB进行序列化,并使用
@xmltransive
注释将属性标记为瞬态。我认为这是正确的,似乎是使用xmlcoder标记道具瞬态的唯一方法。我更新了示例,并添加了指向Oracle文档的链接,解释了使用xmlcoder的瞬态字段。