[英]Remove xsi:type information from xml/json JAXB?
I am using JAXB to convert my domain-model to XML and JSON representations. 我正在使用JAXB将域模型转换为XML和JSON表示形式。 I have Student pojo to convert to XMl/JSON.
我有Student pojo可以转换为XMl / JSON。 It has an
content
property which can be of any data type. 它具有
content
属性,该属性可以是任何数据类型。
Schema definition for it: 架构定义:
<xs:element name="content" type="xs:anyType" />
Thus the java file generated has Object
type for content. 因此,生成的java文件具有内容的
Object
类型。
Student.java: Student.java:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"content"
})
@XmlRootElement(name = "student")
public class Student
extends People
{
................
@XmlElement(required = true)
protected Object content;
}
I marshall using the following code: 我使用以下代码进行编组:
Marshall: 马歇尔:
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);
XML: 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>
xmlns:xsi
and xsi:type="xsd:string">
are coming appended in the content element. xmlns:xsi
和xsi:type="xsd:string">
将追加到content元素中。 I don't want this type information in my XML. 我不希望XML中包含此类信息。
Similarly for JSON it adds the type info: 同样,对于JSON,它添加类型信息:
JSON: JSON:
{
"name" : "Jack n Jones",
"content" : {
"type" : "string",
"value" : "Sid"
}
}
How can I remove the type information and generate XML/JSON according to it's type at run time . 如何在运行时删除类型信息并根据其类型生成XML / JSON。 So whatever type is
content
it get's converted to the type without type information 因此,无论
content
是什么类型,它都会转换为没有类型信息的类型
For example if content is String
then XML: 例如,如果内容为
String
则XML:
<student>
<name>Jack n Jones</name>
<content>Sid</content>
</student>
Passing an java.lang.Object parameter in and JAXB annotated pojo and having no additionally generated meta information after marshalling is not possible. 无法在编组后传递带有java.lang.Object参数且带有JAXB注释的pojo,并且在编组之后不具有其他生成的元信息。 Since the Object is "unknown" type, it needs to be detected and converted during marshalling process, and the metadata will always be generated by the default marshaller.
由于对象是“未知”类型的,因此需要在编组过程中对其进行检测和转换,并且元数据将始终由默认编组器生成。 From this point on, you have three options:
从这一点开始,您有三个选择:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.