Webclient not interpreting enter character correctly in WP7
I've got a problem u开发者_运维知识库sing WebClient.UploadStringAsync method. I've to do a POST request with some info to an external server, and in that request, I've to include the text cointained in a TextBox.
What I do is the following:
Uri url = new Uri("http://www.someweb.com");
string request = "{\"requests\":[\"sendMessage\",{\"body\":\"" + newMessageTextBox.Text + "\"}]}";
WebClient wb = new WebClient();
wb.UploadStringCompleted += new UploadStringCompletedEventHandler(nb_UploadStringCompleted);
wb.UploadStringAsync(url, "Post", request);
There is no problem, but if I include a message with a return, something like "Hello
everybody" the server gives back an error. If I sniff my traffic with Wireshark, I can see my POST request but it is as follows:
"{"requests":["sendMessage",{"body":"Hello
everybody"}]}"
While what I want to send is
"{"requests":["sendMessage",{"body":"Hello\n\neverybody"}]}"
Any ideas??
Thank you all
Yes, you need to perform appropriate JSON escaping. Personally I would use a JSON library for this - I've used Json.NET within Windows Phone 7 and it's worked fine.
You'd build up your request as a JSON object - so without specifying the JSON text form itself at all - and then ask it to format itself into a string (just by calling ToString
). For example:
using System;
using Newtonsoft.Json.Linq;
class Program
{
static void Main(string[] args)
{
string text = "Hello\neverybody";
JObject json = new JObject
{
{ "requests", new JArray
{
new JObject
{
{ "sendMessage", new JObject
{
{ "body", text }
}
}
}
}
}
};
Console.WriteLine(json);
}
}
Output:
{
"requests": [
{
"sendMessage": {
"body": "Hello\neverybody"
}
}
]
}
(Obviously you don't need to use as much whitespace as that if you don't want to. You don't have to use object initializers either.)
EDIT: Okay, with changes as requested:
JObject json = new JObject
{
{ "sid", sid },
{ "version", "0.6" },
{ "requests", new JArray
{
new JArray
{
new JObject
{
{ "sendMessage", new JObject
{
{ "body", text },
{ "recipient", recipient },
{ "legacy", false },
{ "thread_key", threadKey }
}
}
}
}
}
}
};
Result:
{
"sid": "sid",
"version": "0.6",
"requests": [
[
{
"sendMessage": {
"body": "Hello\neverybody",
"recipient": "foo@bar.com",
"legacy": false,
"thread_key": "T1"
}
}
]
]
}
精彩评论