Java 在JAXb中将对象编组为Json时保留属性名
我正在尝试使用JAXb将对象转换为JSON。 对象本身是从XML创建的。 它工作得很好,唯一的问题是用@XmlValue注释的名为“content”的java类属性的名称被重命名为“value”。我的意思是: Xml: 编组以前未编组的对象Java 在JAXb中将对象编组为Json时保留属性名,java,jaxb,marshalling,unmarshalling,Java,Jaxb,Marshalling,Unmarshalling,我正在尝试使用JAXb将对象转换为JSON。 对象本身是从XML创建的。 它工作得很好,唯一的问题是用@XmlValue注释的名为“content”的java类属性的名称被重命名为“value”。我的意思是: Xml: 编组以前未编组的对象 Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); StringReader reader = new StringReader(xmlAsStr
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(xmlAsString);
Outcome outcome= (Outcome) jaxbUnmarshaller.unmarshal(reader);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
StringWriter sw = new StringWriter();
marshaller.marshal(outcome, sw);
这是我在马歇尔之后得到的结果
"outcome" : {
"color" : "red",
"type" : "even",
"value" : "32"
}
正如您所看到的,属性“content”在编组时被转换为“value”
期望结果
"outcome" : {
"color" : "red",
"type" : "even",
"content" : "32"
}
使用Java8
您能帮忙吗?我找到了一个解决方案,Oracle文档中报告了这一点。我希望它能对任何在这方面遇到困难的人有所帮助。您只需添加如下属性:marshaller.setProperty(MarshallerProperties.JSON_VALUE_WRAPPER,“content”);请参阅文档了解其他属性:我找到了一个解决方案,Oracle文档中报告了这一点。我希望它能对任何在这方面遇到困难的人有所帮助。您只需添加如下属性:marshaller.setProperty(MarshallerProperties.JSON_VALUE_WRAPPER,“content”);有关其他属性,请参阅文档:
"outcome" : {
"color" : "red",
"type" : "even",
"value" : "32"
}
"outcome" : {
"color" : "red",
"type" : "even",
"content" : "32"
}