我正在尝试解组我从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
}
unmarshal方法
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
而不是传统UnMarshaller
JAXB
来解决此问题。这是我的代码
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 :(得分:4)
Vanilla JAXB
您目前正在使用JAXB(用于XML绑定的Java体系结构)来处理JSON。它期待XML,因此您收到错误。
EclipseLink JAXB(MOXy)
如果您使用MOXy作为JAXB提供程序,则可以设置一个属性以将其置于JSON模式(请参阅:http://blog.bdoughan.com/2011/08/json-binding-with-eclipselink-moxy.html)。
<强>杰克逊强>
如果您打算使用Jackson,那么您需要使用他们的运行时API。
答案 1 :(得分:2)
您需要将unmarshaller配置为JSON,否则它将默认为XML解析。
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
或者使用JSON解析器(例如Google GSON)进行解组。