Search code examples
c#visual-studio-2013windows-phone

JsonConvert.DeserializeObject issue


in my Windows Phone C# project I'm retrieving info using unirest and trying to deserialize it. 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:

 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?


Solution

  • You have endless loop here. You are creating new BitcoinAPI object and calling Unirest.get() method in its constructor. Then JsonConvert.DeserializeObject() method is creating another BitcoinAPI object so the contructor is called again and again and again... So it never ends.

    My solution is to create static method in BitcoinAPI class and leave empty constructor:

    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().