我正在使用 javax.xml.bind.annotation.XmlRootElement 带注释的对象将其序列化为 XML 字符串。
JAXBContext jc = JAXBContext.newInstance(obj.getClass());
// Marshal the object to a StringWriter
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.example.com/schema.xsd");
StringWriter stringWriter = new StringWriter();
marshaller.marshal(obj, stringWriter);
result = stringWriter.toString();
如何更改 XML 中的某些节点名称,例如我在对象中有“price”,但在生成的 XML 文档中有“thePrice”。
最佳答案
使用 @XmlRootElement
、@XmlElement
和 @XmlAttribute
的 name 属性在 XML 文档中定义不同的名称。
示例:
public class MyClass {
@XmlElement(name="thePrice")
private double price;
}
关于java - 在序列化过程中更改一些对象字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36010432/