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

半腔热情 提交于 2019-12-11 05:28:07

问题


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);


来源:https://stackoverflow.com/questions/24040641/there-was-an-error-deserializing-the-object-of-type-rd-details-%c3%af-%c2%bd19-95-per-pe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!