2013-05-09 141 views

回答

1

這似乎是Jettison的一個隱含的「特徵」它試圖反思實際數據並找出最適合的類型。最好嘗試使用其他一些圖書館,如傑克遜。傑克遜不會嘗試提供一些不必要的幫助來解決這些問題。

2

備註:我是EclipseLink JAXB (MOXy)的領導者,也是JAXB (JSR-222)專家組的成員。

您可以使用MOXy爲此用例提供的JSON綁定。

域模型(根)

import javax.xml.bind.annotation.*; 

@XmlAccessorType(XmlAccessType.FIELD) 
public class Root { 

    int number; 
    String string; 

} 

指定莫西爲您的JSON-綁定提供

在RESTful環境中,您可以指定MOXyJsonProvider作爲MessageBodyReader/MessageBodyWriter爲您的JAX-RS應用

在下面你獨立例如可以指定jaxb.properties文件在同一個包中的以下項您的域模型(見:http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html):

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory 

演示代碼

下面是一個可以運行的獨立示例來證明一切正常:

import java.util.*; 
import javax.xml.bind.*; 
import org.eclipse.persistence.jaxb.JAXBContextProperties; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     Map<String, Object> properties = new HashMap<String, Object>(2); 
     properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json"); 
     properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false); 
     JAXBContext jc = JAXBContext.newInstance(new Class[] {Root.class}, properties); 

     Root root = new Root(); 
     root.number = 1234; 
     root.string = "1234"; 

     Marshaller marshaller = jc.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     marshaller.marshal(root, System.out); 
    } 

} 

輸出

下面是從運行演示代碼的輸出:

{ 
    "number" : 1234, 
    "string" : "1234" 
} 
+0

感謝您的回覆。我無法下載用於導入org.eclipse.persistence.jaxb.JAXBContextProperties的jar文件,並導入org.eclipse.persistence.jaxb.MarshallerProperties,我必須使用它的jar將是有用的,如果我知道從哪裏可以得到的鏈接它。 – user2365956 2013-05-10 09:20:55

+0

@ user2365956 - 您可以在這裏下載EclipseLink:http://www.eclipse.org/eclipselink/downloads/ – 2013-05-10 10:34:40

+3

感謝您的快速響應我面臨着javax.xml.bind.JAXBException:屬性「eclipselink.media-type」不是支持異常 – user2365956 2013-05-13 06:15:01

3

有在投棄型轉換器。默認情況下它使用默認類型轉換器。 如果值是數字類型,則默認類型轉換將刪除雙引號。

要始終使用雙引號,請使用SimpleConverter。

創建系統屬性 - 即 系統。setProperty(「jettison.mapped.typeconverter.class」,「org.codehaus.jettison.mapped.SimpleConverter」);

所以拋棄使用簡單的轉換器和輸出值作爲字符串。

+0

嗨Narendra Reddy,感謝您的重播,我用jackson代替jettison並找到了解決方案。 – user2365956 2013-05-27 07:00:29

相關問題