There was an error deserializing the object of typ

2019-08-08 14:48发布

问题:

When I try and deserialize a JSON string which contains a £ symbol I get the exception.

There was an error deserializing the object of type RD.Details. '�19.95 Per Person' contains invalid UTF8 bytes.

The string which I log is as below:

{
   "Promotions":[
      {
         "Name":"Traditional Afternoon Tea £19.95 Per Person",
         "PromotionId":20175,
         "Quantity":2
      }
   ]
}

This is how I am deserializing:

var responseJsonSerializer = new DataContractJsonSerializer(typeof(TR));
Stream serializedStream;
string serializedString;
byte[] buffer;

using (WebResponse webResponse = webRequest.GetResponse())
{
    serializedStream = webResponse.GetResponseStream();

    using (StreamReader sr = new StreamReader(serializedStream))
    {
        serializedString = sr.ReadToEnd();
    }

    Report.Log("Message Response JSON Object: " + serializedString);

    buffer = Encoding.Default.GetBytes(serializedString);

    using (MemoryStream stream = new MemoryStream(buffer))
    {
        return responseJsonSerializer.ReadObject(stream) as TR;
    }
}

I don't understand why the £ symbol is being seen as invalid utf8. There is nothing wrong with it as far as I can see.

回答1:

Turns out it was just a simple thing of changing the encoding line to

buffer = Encoding.UTF8.GetBytes(serializedString);