在解组Json对象时,java“prolog中不允许内容”
我正在尝试解组从Restful服务响应返回的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对象的方法,还是有其他方法
更新:解决方案
我通过实现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.
# 1 楼答案
您需要将解组器配置为JSON,否则它将默认为XML解析
或者使用JSON解析器(如Google GSON)进行解组
# 2 楼答案
香草JAXB
您当前正在使用JAXB(用于XML绑定的Java体系结构)来处理JSON。它需要XML,因此您将得到一个错误
日食JAXB(MOXy)
如果您使用MOXy作为JAXB提供程序,那么可以设置一个属性将其置于JSON模式(请参阅:http://blog.bdoughan.com/2011/08/json-binding-with-eclipselink-moxy.html)
杰克逊
如果您打算使用Jackson,那么您需要使用他们的运行时API