我正在尝试解码从 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"
}
]
但我正在尝试在我的客户端代码中执行 Unmarshall,它抛出 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.
最佳答案
普通 JAXB
您当前正在使用 JAXB(用于 XML 绑定(bind)的 Java 架构)来处理 JSON。它需要 XML,因此您收到错误。
EclipseLink JAXB (MOXy)
如果您使用 MOXy 作为 JAXB 提供程序,则可以设置一个属性以将其置于 JSON 模式(请参阅:http://blog.bdoughan.com/2011/08/json-binding-with-eclipselink-moxy.html)。
jackson
如果您打算使用 Jackson,那么您需要使用他们的运行时 API。
关于java - 解码 Json 对象时出现 "Content is not allowed in prolog",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20669387/