发布于2021-02-11 01:58 阅读(458) 评论(0) 点赞(19) 收藏(3)
我正在使用JAXB将域模型转换为XML和JSON表示形式。我有Student pojo可以转换为XMl / JSON。它具有content
可以是任何数据类型的属性。
架构定义:
<xs:element name="content" type="xs:anyType" />
因此,生成的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;
}
我使用以下代码进行编组:
马歇尔:
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:
<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
并且xsi:type="xsd:string">
即将附加在content元素中。我不需要XML中的此类信息。
同样,对于JSON,它添加类型信息:
JSON:
{
"name" : "Jack n Jones",
"content" : {
"type" : "string",
"value" : "Sid"
}
}
如何在运行时删除类型信息并根据其类型生成XML / JSON 。所以不管content
它是什么类型,都将转换为没有类型信息的类型
例如,如果内容为String
XML:
<student>
<name>Jack n Jones</name>
<content>Sid</content>
</student>
无法在编组后传递带有java.lang.Object参数且带有JAXB注释的pojo,并且在编组后不具有其他生成的元信息。由于对象是“未知”类型的,因此在编组过程中需要对其进行检测和转换,并且元数据将始终由默认编组器生成。从这一点开始,您有三个选择:
作者:黑洞官方问答小能手
链接:http://www.javaheidong.com/blog/article/92041/b036110ee02f6d638ada/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!