在我的Windows C#项目中,我使用unirest检索信息,并试图反序列化它。我现在拥有的是:
public float btc_to_usd { get; set; }
public BitcoinAPI()
{
HttpResponse<string> response =
Unirest.get("https://montanaflynn-bitcoin-exchange-rate.p.mashape.com/currencies/exchange_rates")
.header("X-Mashape-Key", "<my key here>")
.header("Accept", "text/plain")
.asString();
string json = response.Body;
BitcoinAPI info = JsonConvert.DeserializeObject<BitcoinAPI>(json);
}然后在MainPage.xaml.cs中:
BitcoinAPI api = new BitcoinAPI();
TxtCAmount.Text = api.btc_to_usd.ToString();当我在我的手机上部署它时,它挂在加载屏幕上,应用程序不启动。这里有什么问题?
发布于 2015-02-12 13:00:41
这里有无穷无尽的循环。您正在创建新的BitcoinAPI对象,并在其构造函数中调用Unirest.get()方法。然后JsonConvert.DeserializeObject()方法正在创建另一个BitcoinAPI对象,因此构造器被一次又一次地调用.所以它永远不会结束。
我的解决方案是在BitcoinAPI类中创建静态方法,并保留空构造函数:
public class BitcoinAPI
{
public BitcoinAPI()
{
}
public static BitcoinAPI FromHttp()
{
HttpResponse<string> response =
Unirest.get("https://montanaflynn-bitcoin-exchange-rate.p.mashape.com/currencies/exchange_rates")
.header("X-Mashape-Key", "<my key here>")
.header("Accept", "text/plain")
.asString();
string json = response.Body;
BitcoinAPI info = JsonConvert.DeserializeObject<BitcoinAPI>(json);
return info;
}
}现在,如果您想要从JSON反序列化新的BitcoinAPI对象,只需调用BitcoinAPI.FromHttp()而不是new BitcoinAPI()。
https://stackoverflow.com/questions/28436383
复制相似问题