我想将字符串xml转换为对象类型类。因为我有一个返回Object类型的rest服务。因为我需要根据响应字符串将响应作为动态创建的xml返回。但是当我尝试将字符串xml转换为Object类时,它会显示以下错误:
javax.xml.bind.UnmarshalException:意外元素
我会为你分享我的代码,也许我做错了。
服务方式:
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Object sendReqXML(RequestModel request)
{
try {
XmlAPI.getInstance().addHeader("Content-Type","text/xml; charset=utf-8");
XmlAPI.getInstance().addHeader("SOAPAction",request.getAction());
return XmlAPI.getInstance().post(request.getUrl(), request.getAction(), Parser.loadXML(request.getData()), new CallBackEpul());
}
catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
解析器方法:
public static Object loadXMLToObject(String xml) throws Exception
{
JAXBContext jaxbContext = JAXBContext.newInstance(Object.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
//jaxbUnmarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringReader reader = new StringReader(xml);
Object object = (Object) jaxbUnmarshaller.unmarshal(reader);
//LOGGER.info(car.toString());
return object;
}
xml string:
"<ResultCodes>UnknownError</ResultCodes><Description>Unknown Error</Description>"
我怀疑是否必须在返回类型对象中声明与 @xmlrootelement 相关的内容。因为当我创建具有 @XmlRootElement 和 @XmlElement 标签的模型类并返回自身时,它适用于对象类。
提前致谢。
答案 0 :(得分:0)
我发现将 @Produces 设置为 APPLICATION_XML 就足够了,并返回字符串:
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
@Produces (MediaType.APPLICATION_XML)
public String sendReqXML(RequestModel request)
{
try {
/** JSON API **/
//JsonAPI.getInstance().addHeader("Content-Type","text/xml; charset=utf-8");
//JsonAPI.getInstance().addHeader("SOAPAction",request.getAction());
//JsonAPI.getInstance().post(request.getUrl(), request.getAction(), Parser.loadXML(request.getData()), new CallBackEpul());
/** XML API **/
XmlAPI.getInstance().addHeader("Content-Type","text/xml; charset=utf-8");
XmlAPI.getInstance().addHeader("SOAPAction",request.getAction());
return XmlAPI.getInstance().post(request.getUrl(), request.getAction(), Parser.loadXML(request.getData()), new CallBackEpul());
}
catch (Exception e) {
e.printStackTrace();
return "";
}
}