输出数据从JSON到文本框c#

本文关键字:文本 JSON 数据 输出 | 更新日期: 2023-09-27 18:02:45

我是c#新手,所以这可能是一个非常愚蠢的问题。我的程序是发送一个api请求到服务器,并输出数据到一个文本框。我已经处理了对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["withdraw _balance"]中显示数字到文本框。有人能帮帮我吗?

输出数据从JSON到文本框c#

您不应该再次序列化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"]);
}