gpt4 book ai didi

java - 删除 xsi :type information from xml/json JAXB?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:55:29 28 4
gpt4 key购买 nike

我正在使用 JAXB 将我的域模型转换为 XML 和 JSON 表示。我有 Student pojo 可以转换为 XMl/JSON。它有一个 content 属性,可以是任何数据类型。

它的模式定义:

<xs:element name="content" type="xs:anyType" />

因此生成的 java 文件具有 Object 类型的内容。

学生.java:

 @XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"content"
})
@XmlRootElement(name = "student")
public class Student
extends People
{
................

@XmlElement(required = true)
protected Object content;

}

我使用以下代码编码:

编码(marshal):

    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:xsixsi:type="xsd:string"> 将附加到内容元素中。我不想在我的 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>

最佳答案

在 pojo 中传递 java.lang.Object 参数和 JAXB 注释并且在编码后没有额外生成的元信息是不可能的。由于 Object 是“未知”类型,因此需要在编码过程中对其进行检测和转换,并且元数据将始终由默认编码器生成。从现在开始,您有三个选择:

  1. 白色你的自定义编码器或适配器(有很多WEB 中的示例)
  2. 使用字符串而不是对象(快速和干净解决方案)
  3. 如果你真的必须使用通用的东西,使用“元素”(https://jaxb.java.net/nonav/2.2.4/docs/api/javax/xml/bind/annotation/XmlAnyElement.html)

关于java - 删除 xsi :type information from xml/json JAXB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39510972/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com