2012-04-25 60 views
1

我想通過JSON.NET與JSON.NET在C#.NET應用程序和某個PHP服務器端之間發生一些通信。我在發佈Json字符串,但是我無法訪問(或沒有正確發送)服務器端的字符串。我的$ _POST變量顯示爲空,我不知道用什麼鍵來訪問Json字符串。任何人都可以提出建議Json.NET和PHP通信

我的C#代碼:

TestClass ts = new TestClass("Some Data", 3, 4.5); 
string json = JsonConvert.SerializeObject(ts); 

HttpWebRequest request = 
    (HttpWebRequest)WebRequest.Create("http://localhost/testJson.php"); 
request.Method = "POST"; 
request.ContentType = "application/json"; 
request.ContentLength = json.Length; 

StreamWriter sw = new StreamWriter(request.GetRequestStream()); 
sw.Write(json); 
sw.Close(); 

HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
StreamReader sr = new StreamReader(response.GetResponseStream()); 
string responseJson = sr.ReadToEnd(); 
sr.Close(); 

TestClass returnedTS = 
    JsonConvert.DeserializeObject<TestClass>(responseJson); 

我的PHP代碼:

<?php 
    require("TestClass.php"); 
    $json = json_decode($_POST); 
    $ts = new TestClass(); 
    $ts->someString = $json['someString']; 
    $ts->someDouble = $json['someDouble']; 
    $ts->someInt = $json['someInt']; 
    $return_json = json_encode($ts); 
    echo $return_json; 
?> 

我的輸出:

<b>Warning</b>: json_decode() expects parameter 1 to be string, array given in 
<b>C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\testJson.p 
hp</b> on line <b>4</b><br /> 
{"someString":null,"someInt":null,"someDouble":null} 

回答

2

你必須使用應用程序/ JSON,而不是應用程序/ x-WWW - 形式進行了urlencoded。

也許這有幫助!