2015-02-05 19 views
0

我使用C#發送JSON文章。如果我直接在請求中對值進行硬編碼,那麼一切正常。但我想用變量的形式發送它,但是失敗了。我嘗試了不同的方式,但找不到任何解決方案。 我試圖從ID號爲172024的'num'變量中獲取值,但是在響應中,我得到的是字符串,而不是值。如何在JSON對象中傳遞變量

這裏是我的代碼

static void Main(string[] args) 
{ 
    //Make a Json request 

    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://IPaddress/apibxe_json.php"); 

    httpWebRequest.ContentType = "application/json"; 
    httpWebRequest.Method = "POST"; 

    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) 
    { 
     string num; 
     num = Convert.ToString("172024"); 
     Console.WriteLine(num); 

     string json = "[ { \"connection\" : { \"PS\": \"99778\", \"pr\" : \"******\" }}, {\"execute\" : { \"name\" : \"NewAPI\", \"params\" : { \"Action\" : \"NEW\", \"ID\": \"$num\" , \"Dlr\" : \"&&&&&\"}}}]"; 

     streamWriter.Write(json); 
    } 

    //Get the response 
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) 
    { 
     var responseText = streamReader.ReadToEnd(); 

     JArray jresponse = JArray.Parse(responseText); 

     Console.WriteLine(jresponse); 
    } 
} 
+6

什麼。在地球上。連接字符串就像第一天的東西。我強烈建議你打開一本書,比如CLR Via C#。 '\「PS \」:\「」+ num +「\」,\「pr \」'完成。 – Will 2015-02-05 16:47:27

+0

有趣的是,將「CLR via C#」推薦爲介紹性文本。 :-) – stakx 2015-02-05 16:50:27

+0

對C#使用JSON庫 - 有幾個例子。 – Seti 2015-02-05 16:55:12

回答

1

作爲替代字符串連接,你可能要考慮創建一個類來表示你正在寫入請求主體的JSON和序列化代替,這是一個比較容易使用。

我注意到,你已經在使用JSON.NET--這裏是你會怎麼做,與該庫(使用json2csharp產生類,他們可以使用一些清理,但是這只是一個例子):

public class Connection 
{ 
    public string PS { get; set; } 
    public string pr { get; set; } 
} 

public class Params 
{ 
    public string Action { get; set; } 
    public int ID { get; set; } 
    public string Dlr { get; set; } 
} 

public class Execute 
{ 
    public Execute() 
    { 
     this.Parameters = new Params(); 
    } 

    public string name { get; set; } 

    [JsonProperty("params")] 
    public Params Parameters { get; set; } 
} 

public class Request 
{ 
    public Request() 
    { 
     this.connection = new Connection(); 
     this.execute = new Execute(); 
    } 

    public Connection connection { get; set; } 
    public Execute execute { get; set; } 
} 

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) 
{ 
    var request = new Request(); 

    /* Set other properties as well */ 
    request.execute.Parameters.ID = 172024; 

    string json = JsonConvert.SerializeObject(request); 

    streamWriter.Write(json); 
} 
1

代碼剪斷可能是你(在MVC)有幫助....

public JsonResult LoadName(string temp) 
{ 
     var fromBd=temp+" Bangladesh"; 
     return Json(fromBd,JsonRequestBehavior.AllowGet); 
} 

jQuery函數是....

function(){ 
var temp='From'; 
$.get("/BasicSettings/Ajax/LoadName", { temp: temp}, function (data) { 
      $('span').html(data.fromBd); 
     }); 
} 
+0

我改變了代碼並正在工作。感謝您的幫助,非常感謝。我是C#的新手,並試圖一次學習更多步驟,如果有任何問題,請提供一些初學者中間書籍。 – user3381098 2015-02-05 20:14:27