如何从 JSON http 响应中提取单个元素并将其作为整数传递给 C#
本文关键字:整数 元素 JSON http 响应 单个 提取 | 更新日期: 2023-09-27 18:33:20
我正在编写一个WCF服务,并尝试从以下形成http响应的JSON字符串中提取SMS的值。其余的响应对于我的要求来说是多余的。
{"balance":{"sms":100,"mms":2},"status":"success"}
我目前得到的代码只返回"0"作为平衡的整数。
public class balanceObject
{
public int sms { get; set;}
public int mms {get; set;}
public string status {get; set;}
}
public int balanceRequest()
{
using (var wb = new WebClient())
{
byte[] response = wb.UploadValues("http://api.txtlocal.com/balance/?apiKey=", new NameValueCollection()
{
{"apiKey" , api},
});
string result = System.Text.Encoding.UTF8.GetString(response);
JavaScriptSerializer js = new JavaScriptSerializer();
balanceObject request = (balanceObject)js.Deserialize(result, typeof(balanceObject));
int balance = request.sms;
return balance;
}
}
任何建议将不胜感激。
您的balanceObject
与您的 JSON 不匹配。您的对象应该看起来更像这样:
public class phoneObject
{
public string status {get; set;}
public balanceObject balance {get; set;}
}
public class balanceObject
{
public int sms { get; set;}
public int mms {get; set;}
}
然后,您将像这样检索您的值:
phoneObject request = (phoneObject)js.Deserialize(result, typeof(phoneObject));
int balance = request.balance.sms;
return balance;