2013-12-18 42 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)进行解组。

相关问题