问题描述
好的,
我正在使用 System.Runtime.Serialization
和 DataContractJsonSerialization
.
问题是在请求中我发送了一个带有 &
字符的属性值.比如说,AT&T
,我得到一个错误响应:Invalid JSON Data
.
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.
是的,对于 JSON 格式,这是有效的.但这对我的 POST 请求来说是个问题,因为我需要将它发送到一个服务器,如果该服务器包含一个&符号,则会出现错误响应,因此我在这里.
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
在 System.Web
库中,所以要走的路是使用 Uri.EscapeUriString
.我这样做是为了尝试,但无论如何,如果没有它,所有请求都可以正常工作,除了一个&符号在一个值中.
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.
HttpUtility
类已移植到 Windows Phone SDK,但编码字符串的首选方法仍应为 Uri.EscapeUriString
.
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'?
我应该说我使用
// Convert the string into a byte array.
byte[] postBytes = Encoding.UTF8.GetBytes(data);
将 JSON 转换为 byte[]
并写入 Stream
.还有,
To convert the JSON to a byte[]
and write to the Stream
.And,
request.ContentType = "application/x-www-form-urlencoded";
作为 WebRequest.ContentType
.
那么,我是因为某种原因还是我想念的事情搞砸了?
So, am I messed up for a reason or something I miss?
谢谢.
推荐答案
问题是我正在对包括键在内的整个请求字符串进行编码.我有一个请求 data={JSON}
并且我正在格式化它,但是 {JSON}
部分应该只被编码.
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!
要进入的愚蠢洞.
这篇关于处理发送到 REST Web 服务的 JSON 字符串中的 & 字符的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!