0

在我的程序中,我需要将对象存储在 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();
}
4

2 回答 2

1

看看这个链接。这是一个更新的示例。

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);
    }
}
于 2013-04-21T18:51:17.727 回答
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())));
}
于 2013-04-22T09:13:42.930 回答