将数据从JSON输出到文本框C#

时间:2016-08-17 21:24:40

标签: c# json api json.net

我是C#的新手,所以这可能是一个非常愚蠢的问题。我的程序是向服务器发送api请求并将数据输出到TextBox。对我处理的API的调用,它以JSON格式接收所有信息。

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 [" status"]或JSON [" withdrawable_balance"]中的数字到文本框。有人能帮助我吗?

1 个答案:

答案 0 :(得分: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"]);
}