Monday, 9 September 2013

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

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

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 ambersand & 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
ambersand will response with error, hence here I am.
Url.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 ambersand is in a value.
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.

No comments:

Post a Comment