我有一个用@XmlRootElement
注释的Java类。这个Java类有一个long属性(private long id
),我想返回一个JavaScript客户端。
我按如下方式创建JSON:
MyEntity myInstance = new MyEntity("Benny Neugebauer", 2517564202727464120);
StringWriter writer = new StringWriter();
JSONConfiguration config = JSONConfiguration.natural().build();
Class[] types = {MyEntity.class};
JSONJAXBContext context = new JSONJAXBContext(config, types);
JSONMarshaller marshaller = context.createJSONMarshaller();
marshaller.marshallToJSON(myInstance, writer);
json = writer.toString();
System.out.println(writer.toString());
这将生成:
{"name":"Benny Neugebauer","id":2517564202727464120}
但问题是JavaScript客户端的长值太大了。因此,我想将此值作为字符串返回(不要在Java中将long作为字符串)。
是否有可以生成以下内容的注释(或类似内容)?
{"name":"Benny Neugebauer","id":"2517564202727464120"}
答案 0 :(得分:2)
注意:我是EclipseLink JAXB (MOXy)主管,是JAXB (JSR-222)专家组的成员。
以下是如何使用MOXy作为JSON提供程序来完成此用例。
<强> myEntity所强>
您可以使用long
对@XmlSchemaType(name="string")
媒体资源进行注释,以表明它应该被编组为String
。
package forum11737597;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class MyEntity {
private String name;
private long id;
public MyEntity() {
}
public MyEntity(String name, long id) {
setName(name);
setId(id);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlSchemaType(name="string")
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
<强> jaxb.properties 强>
要将MOXy配置为JAXB提供程序,您需要在与域模型相同的包中包含名为jaxb.properties
的文件(请参阅:http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)。
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
<强>演示强>
我修改了示例代码,以显示使用MOXy时的样子。
package forum11737597;
import java.io.StringWriter;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
MyEntity myInstance = new MyEntity("Benny Neugebauer", 2517564202727464120L);
StringWriter writer = new StringWriter();
Map<String, Object> config = new HashMap<String, Object>(2);
config.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
config.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
Class[] types = {MyEntity.class};
JAXBContext context = JAXBContext.newInstance(types, config);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(myInstance, writer);
System.out.println(writer.toString());
}
}
<强>输出强>
以下是运行演示代码的输出:
{"id":"2517564202727464120","name":"Benny Neugebauer"}
了解更多信息