简体   繁体   English

JsonConvert.DeserializeObject问题

[英]JsonConvert.DeserializeObject issue

in my Windows Phone C# project I'm retrieving info using unirest and trying to deserialize it. 在我的Windows Phone C#项目中,我正在使用unirest检索信息并尝试反序列化它。 Here's what I have: 这就是我所拥有的:

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);

    }

And then in MainPage.xaml.cs: 然后在MainPage.xaml.cs中:

 BitcoinAPI api = new BitcoinAPI();
 TxtCAmount.Text = api.btc_to_usd.ToString();

And when I'm deploying it on my phone it hangs on loading screen and app doesn't launch. 当我在手机上部署它时,它会挂在加载屏幕上并且应用程序无法启动。 What's the issue here? 这是什么问题?

You have endless loop here. 你在这里有无尽的循环。 You are creating new BitcoinAPI object and calling Unirest.get() method in its constructor. 您正在创建新的BitcoinAPI对象并在其构造函数中调用Unirest.get()方法。 Then JsonConvert.DeserializeObject() method is creating another BitcoinAPI object so the contructor is called again and again and again... So it never ends. 然后JsonConvert.DeserializeObject()方法正在创建另一个BitcoinAPI对象,所以一次又一次地调用构造函数......所以它永远不会结束。

My solution is to create static method in BitcoinAPI class and leave empty constructor: 我的解决方案是在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;
    }
}

Now, if you want new BitcoinAPI object deserialized from JSON, just call BitcoinAPI.FromHttp() instead of new BitcoinAPI() . 现在,如果你想从JSON反序列化新的BitcoinAPI对象,只需调用BitcoinAPI.FromHttp()而不是new BitcoinAPI()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM