2016-08-17 5 views
0

私はC#を初めて使用しているので、これは非常にばかげた質問かもしれません。私のプログラムは、サーバにapiリクエストを送信し、そのデータをTextBoxに出力することです。私が処理したAPIへの呼び出しは、すべての情報をJSON形式で受け取ります。JSONからTextboxへのデータ出力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; 
    } 
} 

ウェブAPI戻り、この:

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

問題は、私はJSON [ "ステータス"]またはJSON [ "withdrawable_balance"]で数字だけを表示する方法がわからないですテキストボックス。誰か助けてくれますか?あなたが再びjson stringをシリアル化することになっていません

+0

あなたは今、個々の要素を抽出するために、あなたが受け取るJSONをパースする必要があります。 var obj = JObject.Parse(json)のようなものです。 var balance =(文字列)obj ["data"] ["withdrawable_balance"]; –

答えて

2

、代わりにあなたはそれをデシリアライズしたい:

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

ありがとうございます。唯一のことはレスポンス["data"] ["withdrawable_balance"]は文字列でした。しかし、すべての助けに感謝します。 –

関連する問題