2012-07-31 59 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

相關問題