2012-07-31 51 views
3

我有一个用@XmlRootElement注解的Java类。这个Java类有一个很长的属性(private long id),我想返回到JavaScript客户端。如何使用JAXB将长整型属性作为JSON字符串值返回

我创建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中使用长字符串)。

是否有可以生成以下内容的注释(或类似内容)?

{"name":"Benny Neugebauer","id":"2517564202727464120"} 

回答

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

要配置莫西为您的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 

演示

我已经修改了你的示例代码,以显示它会是什么样子,如果你使用的莫西。

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"} 

更多信息

+1

太棒了!谢谢你这个非常详细的答案。使用EclipseLink MOXY保持良好的工作和运气! – 2012-07-31 15:16:16

相关问题