选择要序列化的属性

时间:2013-04-21 18:50:34

标签: 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 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();
}

2 个答案:

答案 0 :(得分:1)

结帐this link。这是一个更新的例子。

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

答案 1 :(得分:1)

我选择使用带注释的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())));
}