我的代码工作(是的!)将json发送到服务器..会对重构的任何想法表示感谢
1)我的C#代码将此json发送到服务器
{\ “名字\”:\ “比尔\”,\ “姓氏\”:\ “盖茨\” \ “电子邮件\”:\ “asdf@hotmail.com \”,\ “deviceUUID \”: \ “ABCDEFGHIJKLMNOPQRSTUVWXYZ \”}
我必须摆脱服务器端的斜线......不好。
2)我正在使用application / x-www-form-urlencoded并且可能想要使用application / json
Person p = new Person();
p.firstName = "Bill";
p.lastName = "Gates";
p.email = "asdf@hotmail.com";
p.deviceUUID = "abcdefghijklmnopqrstuvwxyz";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri + "newuser.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//TODO request.ContentType = "application/json";
JavaScriptSerializer serializer = new JavaScriptSerializer();
string s = serializer.Serialize(p);
textBox3.Text = s;
string postData = "json=" + HttpUtility.UrlEncode(s);
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close ();
WebResponse response = request.GetResponse();
//textBox4.Text = (((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd ();
textBox4.Text += responseFromServer;
reader.Close ();
dataStream.Close ();
response.Close ();
服务器上的PHP代码:
$inbound = $_POST['json'];
// this strips out the \
$stripped = stripslashes($inbound);
$json_object = json_decode($stripped);
echo $json_object->{'firstName'};
echo $json_object->{'lastName'};
echo $json_object->{'email'};
echo $json_object->{'deviceUUID'};
答案 0 :(得分:1)
你确定那里有那些斜杠吗?这是C#编码字符串以供显示的调试器视图,但JavaScriptSerializer发出的实际值在标识符中没有任何斜杠。唯一被转义的是JSON值内容......
答案 1 :(得分:1)
我发现这很容易使用:http://james.newtonking.com/archive/2008/02/11/linq-to-json-beta.aspx和http://james.newtonking.com/projects/json-net.aspx
答案 2 :(得分:0)
好主意......我已经检查了VS,并在textBox3.Text = s上设置断点; 然后将鼠标悬停在上一行s上。它显示了这个:
s =“{\”firstName \“:\”Bill \“,\”lastName \“:\”Gates \“,\”email \“:\”asdf @ hotmail.com \“,\”deviceUUID \ “:\” ABCDEFGHIJKLMNOPQRSTUVWXYZ \ “}”
所以,我也检查了PHP方面:
$inbound = $_POST['json'];
var_dump($inbound);
的字符串(124) “{\” 名字\ “:\” 比尔\ “\ ”姓氏\“:\ ”盖茨\“,\ ”电子邮件\“:\ ”asdf@hotmail.com \“,\ ”deviceUUID \“:\” ABCDEFGHIJKLMNOPQRSTUVWXYZ \ “}”
答案 3 :(得分:0)
JSON.NET非常棒且值得一试 - 它比JavaScriptSerializer更好地做了一些事情,但我知道JavaScriptSerializer(和任何其他JSON序列化程序)不会使用斜杠输出标识符。它是无效的JSON。
答案 4 :(得分:0)
搞定了
有两个问题:
PHP服务器正在转发传入的数据,所以我不得不使用stripslashes。
http://nz.php.net/magic_quotes
同样在VS的房产上空盘旋,显示大幅削减但是
Debug.Write(s);
示:
[{"categoryid":"1","name":"funny","serverimageid":"1","dateuploaded":"2008-11-17 16:16:41","enabled":"\u0001"},{"categoryid":"2","name":"happy","serverimageid":"2","dateuploaded":"2008-11-17 16:17:00","enabled":"\u0001"},{"categoryid":"3","name":"sad","serverimageid":"3","dateuploaded":"2008-11-16 16:17:13","enabled":"\u0001"}]
谢谢大家。