我的代码可以工作(耶!)它将json发送到服务器..如果您对重构有任何想法,将不胜感激
1)我的C#代码将这个json发送到服务器
{\“名字\”:\“比尔\”,\“姓氏\”:\“盖茨\”,\“电子邮件\”:\“asdf@hotmail.com\”,\"deviceUUID\":\"abcdefghijklmnopqrstuvwxyz\"}
我必须去掉服务器上的斜杠,side....not很好。
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'};发布于 2008-11-21 02:37:47
你确定你有那些斜杠吗?这是调试器视图,C#对字符串进行编码以供显示,但是从JavaScriptSerializer输出的实际值在标识符中没有任何斜杠。唯一被转义的是JSON值内容...
发布于 2008-11-21 03:16:40
我发现这很容易使用:http://james.newtonking.com/archive/2008/02/11/linq-to-json-beta.aspx和http://james.newtonking.com/projects/json-net.aspx
发布于 2008-11-21 02:56:49
好主意..。我已经检查了VS,并在textBox3.Text = s;上设置了断点,然后将鼠标悬停在前一行s上。
S=“{\”名字\“:\”比尔\“,\”姓氏\“:\”盖茨\“,\”电子邮件\“:\”asdf@hotmail.com\“,\"deviceUUID\":\"abcdefghijklmnopqrstuvwxyz\"}”
所以,我也检查了PHP端:
$inbound = $_POST['json'];
var_dump($inbound);字符串(124)“{\”名字\“:\”比尔\“,\”姓氏\“:\”盖茨\“,\”电子邮件\“:\”asdf@hotmail.com\“,\"deviceUUID\":\"abcdefghijklmnopqrstuvwxyz\"}"
https://stackoverflow.com/questions/307619
复制相似问题