zdarsky.peter
zdarsky.peter

Reputation: 6277

Choose which properties will be serialized

in my program I need to store object in XML. But I dont want all properties to be serialized to xml. How should I do that ?

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

Upvotes: 0

Views: 97

Answers (2)

zdarsky.peter
zdarsky.peter

Reputation: 6277

I choose to use JAXB serialization with annotations. It was the best and easiest option. Thank all of you for your help.

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

Upvotes: 1

clav
clav

Reputation: 4251

Check out this link. Here's an updated example.

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

Upvotes: 1

Related Questions