Proper way to handle the ampersand character in JSON string send to REST web service

二次信任 提交于 2020-01-01 06:31:26

问题


OK,

I am using the System.Runtime.Serialization and the DataContractJsonSerialization.

The problem is that in the request I send a value of a property with the & character. Say, AT&T, and I get a response with error: Invalid JSON Data.

I thought that the escaping would be done inside the library but now I see that the serialization is left untouched the ampersand & character.

Yes, for a JSON format this is valid. But it will be a problem to my POST request since I need to send this to a server that if contains an ampersand will response with error, hence here I am.

HttpUtility.HtmlEncode is in the System.Web library and so the way to go is using Uri.EscapeUriString. I did this to try, but anyway, and without it all requests are working fine, except an ampersand is in a value.

EDIT: HttpUtility class is ported to the Windows Phone SDK but the prefer way to encode a string should be still Uri.EscapeUriString.

First thought was to get hands dirty and start replacing the special character which would cause a problem in the server, but, I wonder, is there another solution I should do, that it would be efficient and 'proper'?

I should tell that I use

// Convert the string into a byte array.
byte[] postBytes = Encoding.UTF8.GetBytes(data);

To convert the JSON to a byte[] and write to the Stream. And,

request.ContentType = "application/x-www-form-urlencoded";

As the WebRequest.ContentType.

So, am I messed up for a reason or something I miss?

Thank you.


回答1:


The problem was that I was encoding the whole request string including the key. I had a request data={JSON} and I was formatting it, but the {JSON} part should only be encoded.

string requestData = "data=" + Uri.EncodeDataString(json) // worked perfect!

Stupid hole to step into.




回答2:


Have you tried replacing the ampersand with & for the POST?



来源:https://stackoverflow.com/questions/18707854/proper-way-to-handle-the-ampersand-character-in-json-string-send-to-rest-web-ser

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