gpt4 book ai didi

java - 选择要序列化的属性

转载 作者:行者123 更新时间:2023-12-02 07:05:46 24 4
gpt4 key购买 nike

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

最佳答案

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

关于java - 选择要序列化的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16134920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com