在序列化期间更改某些对象字段名称 [英] Changing some Object field names during serialization

查看:143
本文介绍了在序列化期间更改某些对象字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用javax.xml.bind.annotation.XmlRootElement注释对象将其序列化为XML字符串。

I am using javax.xml.bind.annotation.XmlRootElement annotated object to serialize it into XML string.

        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中的某些节点名称,就像我在对象中有价格一样,但是生成的XML文档中的thePrice。

How to change some node name in the XML, so like I have "price" in the object, but "thePrice" in the XML document generated.

推荐答案

使用 @XmlRootElement的name属性 @XmlElement @XmlAttribute 在XML文档中定义一个不同的名称。

Use the name property of @XmlRootElement, @XmlElement and @XmlAttribute to define a different name in the XML document.

示例:

public class MyClass {
     @XmlElement(name="thePrice")
     private double price;
 }

这篇关于在序列化期间更改某些对象字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆