Reputation: 4124
I am de-serializing string to My classes. for that i have written a generic method
private T ExtractResponse<T>(string response) where T : class
{
T obj = null;
if (!String.IsNullOrEmpty(response))
{
var serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(response))
{
obj = (T)serializer.Deserialize(reader);
}
}
return obj;
}
Previously i were just having ascii character so no Problem in deseriailizing. Now i am getting some non ascii characters in my responses like [2J2J] Due to that my xml is not deseriailizing into object. My xml document encoding is "ISO-8859-1" What change should i do in above logic method so that it should work correctly with my encoding.
Upvotes: 0
Views: 33
Reputation: 4124
I got a close answer to my question from my similar msdn forum post.Answer is
Your method will always use Unicode (UTF-16) as a String .NET is encoded in Unicode - and the StringReader has no possibility to pass any other encoding for that reason.
If you want to use different encodings your method should accept a MemoryStream or a byte array. The method that creates the response will have to rewritten that it writes the data into a MemoryStream with the correct encoding, and returns resulting bytes.
Then you can use a StreamReader and pass a different encoding, for example:
private T ExtractResponse<T>(byte[] response) where T : class
{
T obj = null;
if (response != null && response.Length > 0)
{
var serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StreamReader(
new MemoryStream(response),
System.Text.Encoding.GetEncoding("iso-8859-1")))
{
obj = (T)serializer.Deserialize(reader);
}
}
return obj;
}
You could also add the encoding as an (optional) second parameter.
Note: For a Xml Document you can use a XmlReader for the XmlSerializer. That can detect the encoding from the document declaration.
Upvotes: 0
Reputation: 1324
Looks like you got your answer over at the MSDN Forums already. But in case someone else stumbles on this...
Specify the encoding you want in your StringReader, like so:
using (TextReader reader = new StringReader(response, System.Text.Encoding.GetEncoding("iso-8859-1")))
Upvotes: 1