2013-12-18 44 views
2

我想解開Json對象,我從Restful Service響應回來。但是在解組的時候拋出異常呢?「內容不被允許在序言中」,而解組Json對象

MyClass.java

@XmlRootElement 
@XmlAccessorType(XmlAccessType.FIELD) 
public class MyClass 
{ 
    @XmlElement(name="id") 
    private String id; 

    @XmlElement(name="f-name") 
    private String fname; 


    @XmlElement(name="l-name") 
    private String lname; 

// getters and setters for these 

} 

解組方法

JAXBContext context = JAXBContext.newInstance(MyClass.class); 
Unmarshaller unMarshaller = context.createUnmarshaller(); 
URL url = new URL("http://localhost:8080/service-location"); 
HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
connection.setRequestMethod("GET"); 
connection.setRequestProperty("Accept", "application/json"); 
connection.connect(); 
MyClass myclass=(MyClass)unMarshaller.unmarshal(connection.getInputStream()); 

,當我試圖使用一些瀏覽器客戶端我越來越像下面適當的反應。

[ 
    { 
     "fname": "JOHN", 
     "lname": "Doe", 
     "id": "abc123"   
    } 
] 

但我試圖做和解組在我的客戶端代碼它拋出SAXParserException

Caused by: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog. 

我不知道我做錯了。這種方式可以解開JSON對象嗎?或者還有其他方法可以做到嗎?

UPDATE:解

我通過實施Jackson's ObjectMapper而非JAXB常規UnMarshaller固定這一點。這裏是我的代碼

ObjectMapper mapper = new ObjectMapper(); 
JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, MYClass.class); 
mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); 
list = mapper.readValue(jsonString, type); // JsonString is my response converted into String of json data. 
+0

您已指定您的JSON作爲數組,嘗試不使用[和] –

+0

我用有效的JSON嘗試作爲一個測試案例。它仍然拋出這個錯誤。 – SRy

+0

@SotiriosDelimanolis ..我測試BOM的但沒有發現任何東西。所以,從這個角度來看,這一切都很好。 – SRy

回答

4

香草JAXB

您目前正在使用JAXB(Java體系XML綁定)來處理JSON。它期待XML,所以你得到一個錯誤。

的EclipseLink JAXB(莫西)

如果您正在使用莫西爲您的JAXB提供有您可以設置把它放在JSON模式(參見:http://blog.bdoughan.com/2011/08/json-binding-with-eclipselink-moxy.html)的屬性。

傑克遜

如果您打算使用傑克遜,那麼你需要用自己的運行時API。

+0

是的。我嘗試了您的博客中的一些示例。他們工作得很好。但是我們被綁定到傑克遜,所以現在不能更改版本。更多的是我們在Jboss上運行,所以不知道有什麼搞砸了 – SRy

+0

@SRy - 可以理解。 Jackson可以解釋一些JAXB元數據,但他們有自己的運行時API:http://wiki.fasterxml.com/JacksonJAXBAnnotations –

+1

感謝您指點我正確的方向。我通過傑克遜的本地objectMapper修復了它。順便說一下EclipseLink Moxy JaxB實現方面的出色工作。 – SRy

2

您需要配置解組器爲JSON,否則它將默認爲XML解析。或者使用JSON解析器(如Google GSON)進行解組。

相關問題