Question

I have no problem deserializing an xml into my class while using the following code. I was wondering if it was possible to use the same code on a local file, as our source files are saved locally for archival purposes and are occasionally reprocessed.

This works for remote xml but not for local xml:

RestRequest request = new RestRequest();
var client = new RestClient();

//doesnt work
client.BaseUrl = directory;
request.Resource = file;

//works
client.BaseUrl = baseURL;
request.Resource = url2;


IRestResponse<T> response = client.Execute<T>(request);
return response.Data;

Is there a way to use RestSharp from a local file? I was going to try to use the same function regardless of whether the xml is local or remote and just pass it the location of the xml to read.

Était-ce utile?

La solution 2

This is not possible with standard functionality. For example "file://" URLs do not work with RestSharp.

I would recommend using RestSharp do get the returned data from a Uri and having another function to deserialize this data into an object.

You can use the same funcion then to deserialize from file data.

RestSharp is a library to do REST calls, not to deserialize from arbitrary sources. Even if there is a possibility to make RestSharp believe it is talking to a website instead of a file, it would be a hack.

If you need it you could still use the XmlDeserializer from RestSharp. It expects a IRestResponse object, but it only uses the Content property from it, so it should be easy to create. It still feels like a hack though and there are more than enough other XmlSerializers out there that will do a great job

Autres conseils

This is in fact possible using built in JsonDeserializer class as below. I have used this method to stub API response for testing.

// Read the file

string fileContents = string.Empty;

using (System.IO.StreamReader reader = new System.IO.StreamReader(@"C:\Path_to_File.txt"))
{
    fileContents = rd.ReadToEnd();
}

// Deserialize
RestResponse<T> restResponse = new RestResponse<T>();

restResponse.Content = fileContents;

RestSharp.Deserializers.JsonDeserializer deserializer = new RestSharp.Deserializers.JsonDeserializer();

T deserializedObject = deserializer.Deserialize<T>(restResponse);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top