Sid*_*kha 8 java xml jaxb xml-serialization jackson
我正在使用JAXB将我的域模型转换为XML和JSON表示.我有学生pojo转换为XMl/JSON.它具有content可以是任何数据类型的属性.
它的模式定义:
<xs:element name="content" type="xs:anyType" />
Run Code Online (Sandbox Code Playgroud)
因此,生成的java文件具有Object内容类型.
Student.java:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"content"
})
@XmlRootElement(name = "student")
public class Student
extends People
{
................
@XmlElement(required = true)
protected Object content;
}
Run Code Online (Sandbox Code Playgroud)
我使用以下代码进行编组:
马歇尔:
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "name-binding.xml");
this.ctx = JAXBContext.newInstance("packagename",
packagename.ObjectFactory.class.getClassLoader(), properties);
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE,media-type);
marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT,true);
marshaller.setProperty(MarshallerProperties.JSON_REDUCE_ANY_ARRAYS, true);
StringWriter sw = new StringWriter();
marshaller.marshal(object, sw);
Run Code Online (Sandbox Code Playgroud)
XML:
<student>
<name>Jack n Jones</name>
<content xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:string">Sid</content>
</student>
Run Code Online (Sandbox Code Playgroud)
xmlns:xsi并将xsi:type="xsd:string">附加在内容元素中.我不想在我的XML中使用此类型信息.
类似地,对于JSON,它添加了类型信息:
JSON:
{
"name" : "Jack n Jones",
"content" : {
"type" : "string",
"value" : "Sid"
}
}
Run Code Online (Sandbox Code Playgroud)
如何在运行时根据类型删除类型信息并生成XML/JSON .所以无论什么类型content它都被转换为没有类型信息的类型
例如,如果内容是StringXML:
<student>
<name>Jack n Jones</name>
<content>Sid</content>
</student>
Run Code Online (Sandbox Code Playgroud)
小智 2
在 JAXB 注释的 pojo 中传递 java.lang.Object 参数并且在编组后没有额外生成的元信息是不可能的。由于Object是“未知”类型,因此需要在编组过程中对其进行检测和转换,并且元数据将始终由默认编组器生成。从此时起,您有三个选择:
| 归档时间: |
|
| 查看次数: |
1659 次 |
| 最近记录: |