首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JsonConvert.DeserializeObject问题

JsonConvert.DeserializeObject问题
EN

Stack Overflow用户
提问于 2015-02-10 16:13:20
回答 1查看 424关注 0票数 0

在我的Windows C#项目中,我使用unirest检索信息,并试图反序列化它。我现在拥有的是:

代码语言:javascript
复制
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中:

代码语言:javascript
复制
 BitcoinAPI api = new BitcoinAPI();
 TxtCAmount.Text = api.btc_to_usd.ToString();

当我在我的手机上部署它时,它挂在加载屏幕上,应用程序不启动。这里有什么问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-12 13:00:41

这里有无穷无尽的循环。您正在创建新的BitcoinAPI对象,并在其构造函数中调用Unirest.get()方法。然后JsonConvert.DeserializeObject()方法正在创建另一个BitcoinAPI对象,因此构造器被一次又一次地调用.所以它永远不会结束。

我的解决方案是在BitcoinAPI类中创建静态方法,并保留空构造函数:

代码语言:javascript
复制
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()

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28436383

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档