简体   繁体   中英

Error while deserializing an XML document using RestSharp

I am trying to deserialize the following XML response using RestSharp:

<?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. Line 1, position 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. 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!

Thanks again.

Well, the exception message is pretty clear: Line 1 has invalid syntax:

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

The XML should probably look like this instead:

<?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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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