简体   繁体   English

使用RestSharp反序列化XML文档时出错

[英]Error while deserializing an XML document using RestSharp

I am trying to deserialize the following XML response using RestSharp: 我正在尝试使用RestSharp反序列化以下XML响应:

<?xml version="1.0" encoding="UTF-8"?>
<ns0:payload xmlns:ns0="http://www.website.co.za/JSON_Token">
<ns0:content>
    <ns0:reason>token successfully created</ns0:reason>
    <ns0:success>true</ns0:success>
    <ns0:authDetails>
        <ns0:accessToken>feefaee94822a92ca7f134f74588cc69081b0e94</ns0:accessToken>
        <ns0:expiresIn>604800</ns0:expiresIn>
        <ns0:refreshToken>bc036cba4d346bf76809e143879cb8fb6983940c</ns0:refreshToken>
    </ns0:authDetails>
</ns0:content>

This is a snapshot of my code: 这是我的代码的快照:

IRestResponse response = client.Execute(request);

RestSharp.Deserializers.XmlDeserializer deserial = new RestSharp.Deserializers.XmlDeserializer();

payload apiresponse = deserial.Deserialize<payload>(response);

And this is the error that I am getting: 这是我得到的错误:

An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll Additional information: Data at the root level is invalid. System.Xml.dll中发生了类型为'System.Xml.XmlException'的未处理异常。其他信息:根级别的数据无效。 Line 1, position 1. 第1行,位置1。

any ideas what I am doing wrong? 有什么想法我做错了吗?

Thanks for all the replies. 感谢所有的答复。

I did some more investigation and after printing the content of the response to a string, it turned out that RestSharp was actually converting it from XML to JSON. 我进行了更多调查,将响应的内容打印到字符串后,事实证明RestSharp实际上是将其从XML转换为JSON。 No idea why it was doing that (i certainly wasn't specifying it, perhaps it's a default setting). 不知道为什么要这么做(我当然没有指定,也许这是默认设置)。

So because the response was a JSON then the XML deserializing was obviously throwing an error! 因此,由于响应是JSON,因此XML反序列化显然会引发错误!

Thanks again. 再次感谢。

Well, the exception message is pretty clear: Line 1 has invalid syntax: 好吧,异常消息很清楚:第1行的语法无效:

<ns0:payload xmlns:ns0="http://www.website.co.za/JSON_Token">

The XML should probably look like this instead: XML应该看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<ns0:payload xmlns:ns0="http://www.website.co.za/JSON_Token">
    <ns0:content>
        <ns0:reason>token successfully created</ns0:reason>
        <ns0:success>true</ns0:success>
        <ns0:authDetails>
            <ns0:accessToken>feefaee94822a92ca7f134f74588cc69081b0e94</ns0:accessToken>
            <ns0:expiresIn>604800</ns0:expiresIn>
            <ns0:refreshToken>bc036cba4d346bf76809e143879cb8fb6983940c</ns0:refreshToken>
        </ns0:authDetails>
    </ns0:content>
</ns0:payload>

If you cannot change how the XML response is generated, you should pre-process the XML using common string-manipulation since it is invalid XML and hence cannot be parsed using standard tools. 如果您无法更改XML响应的生成方式,则应使用通用的字符串操作对XML进行预处理,因为它是无效的XML,因此无法使用标准工具进行解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM