我有个问题。你能帮帮我吗。我有一个应用程序: CXF+Spring+JAXB+REST。我尝试使用JSONProvider
类生成响应--有一个bean类:
@XmlRootElement
class Foo {
@XmlElement
private String bar;
}
当我设置为字段值时:
setBar("true")
或
setBar("false");
JSONProvider返回给我:
"bar":false
但是,我想
"bar":"false"
因为我使用字符串类型。我该拿它怎么办?
发布于 2012-06-22 09:08:42
备注:,我是EclipseLink JAXB (MOXy)的负责人,也是JAXB (JSR-222)专家组的成员。
JAXB (JSR-222)规范不包括JSON绑定。在REST/ JAXB上下文中,应该由提供者将JAXB映射规则应用到JSON表示中。目前正在使用3种不同的方法:
"true"
类型的情况下接收字符串,因此它决定将其表示为JSON布尔值,因为它可能是大多数时候所需的输出。MOXy示例
根
下面是一个带有String
和boolean
字段的域对象。我还添加了带有@XmlSchemaType
注释的字段,这些字段可以用来覆盖默认表示。
package forum11145933;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
String barString;
boolean barBoolean;
@XmlSchemaType(name="boolean")
String barStringWithXmlTypeBoolean;
@XmlSchemaType(name="string")
boolean barBooleanWithXmlTypeString;
}
jaxb.properties
要将MOXy指定为JAXB提供程序,需要在与域模型相同的包中添加一个名为jaxb.properties
的文件,其中包含以下条目:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Demo
下面的代码演示如何将域对象封送到JSON。注意,MOXy上不存在编译时依赖关系。
package forum11145933;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Root root = new Root();
root.barString = "true";
root.barBoolean = true;
root.barStringWithXmlTypeBoolean = "true";
root.barBooleanWithXmlTypeString = true;
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty("eclipselink.media-type", "application/json");
marshaller.marshal(root, System.out);
}
}
输出
下面是运行Demo
代码的输出。注意如何正确地写出boolean
和String
属性。还请注意@XmlSchemaType
注释的使用如何允许我们将boolean
封送为String
,反之亦然。
{
"root" : {
"barString" : "true",
"barBoolean" : true,
"barStringWithXmlTypeBoolean" : true,
"barBooleanWithXmlTypeString" : "true"
}
}
MOXy & JAX-RS
MOXy包括MOXyJsonProvider
,可用于在JAX环境中启用MOXy作为JSON提供程序:
https://stackoverflow.com/questions/11145933
复制