Reputation: 37
I'm new to C#, so this may be a very stupid question. My program is to send an api request to a server and output the data to a TextBox. The call to the API I have handled and it receives all the information in JSON format.
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;
}
}
The Web API returns this:
{ "status" : "success",
"data" : {
"available_balance" : "0",
"pending_withdrawals" : "0.0000",
"withdrawable_balance" : "0"
}
}
The problem is I don't know how to display just the numbers in JSON["status"] or JSON["withdrawable_balance"] to the textbox. Can someone help me?
Upvotes: 0
Views: 3631
Reputation: 14477
You aren't supposed to serialize a json string
again, instead you want to deserialize it :
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"]);
}
Upvotes: 3