2016-08-17 18 views
0

我是C#的新手,所以這可能是一個非常愚蠢的問題。我的程序是向服務器發送api請求並將數據輸出到TextBox。對我所處理的API的調用,它以JSON格式接收所有信息。從JSON輸出數據到文本框C#

public void button2_Click(object sender, EventArgs e) 
{   
    var OTPSCODE = new TOTP("CODE"); 
    string API = "API KEY"; 
    string REQ; 

    REQ = SendRequest("WEBSITE"+API+"&code="+OTPSCODE.now()); 

    if (REQ != null) 
    { 
     //MessageBox.Show(REQ, "Hey there!", MessageBoxButtons.OK, MessageBoxIcon.Information); 
     string json = Newtonsoft.Json.JsonConvert.SerializeObject(REQ); 

     BalanceTB.Text = // This is Where I want the output to be; 
    } 
} 

private string SendRequest(string url) 
{ 
    try 
    { 
     using (WebClient client = new WebClient()) 
     { 
      return client.DownloadString(new Uri(url)); 
     } 
    } 
    catch (WebException ex) 
    { 
     MessageBox.Show("Error while receiving data from the server:\n" + ex.Message, "Something broke.. :(", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); 
     return null; 
    } 
} 

在Web API返回此:

{ "status" : "success", 
"data" : { 
"available_balance" : "0", 
"pending_withdrawals" : "0.0000", 
"withdrawable_balance" : "0" 
} 
} 

的問題是我不知道如何在JSON [ 「狀態」]或JSON只顯示號碼[ 「withdrawable_balance」]的文本框。有人能幫我嗎?

+0

你必須分析你現在爲了提取單個元素收到JSON。像var obj = JObject.Parse(json); var balance =(string)obj [「data」] [「withdrawable_balance」]; –

回答

2

你不應該再序列化json string,而不是要反序列化:

var request = "WEBSITE"+API+"&code="+OTPSCODE.now(); 
var json = SendRequest(request); 
if (json != null) 
{ 
    //MessageBox.Show(REQ, "Hey there!", MessageBoxButtons.OK, MessageBoxIcon.Information); 
    var response = Newtonsoft.Json.Linq.JObject.Parse(json); 

    BalanceTB.Text = string.Format("{0} or {1}", 
     (string)response["status"], 
     (int)response["data"]["withdrawable_balance"]); 
} 
+0

感謝您的支持。唯一的是響應[「數據」] [「withdrawable_balance」]是一個字符串。但感謝所有的幫助。 –