简体   繁体   中英

Why web api data deserialized from json returned as null and not displayed in view?

I am new to JSON serialization and deserialization, currently trying to deserialize a set of data from a Web API call. The data is visible until the deserialization, but when it's sent to the view, it's showing "null".

Model:

public class Currency
{
    public string Rates { get; set; }
}

Controller:

public class CurrencyController:Controller
{ 
    string Baseurl = "https://api.exchangeratesapi.io/";

    public async Task<ActionResult> Index()
    {
        Currency CurencyInfo = new Currency();

        using (HttpClient client = new HttpClient())
        {
            client.BaseAddress = new Uri(Baseurl);
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage Result = await client.GetAsync("https://api.exchangeratesapi.io/latest");

            if (Result.IsSuccessStatusCode)
            {
                // Storing the response details received from Web API 
                var CurrencyResponse = Result.Content.ReadAsStringAsync().Result;

                // Deserializing the response received from Web API and storing into the CurrencyInfo 
                CurencyInfo = JsonConvert.DeserializeObject<Currency>((JObject.Parse(CurrencyResponse)["rates"]).ToString());
            }

            // returning the Currency Info to view  
            return View(CurencyInfo);
        }
    }
}

Have you check the naming? Could be issue that from json you get smaller caps variable

Your Currency Class is Incorrect.It does not include all the properties to bind. Looking at the JSON result returned by https://api.exchangeratesapi.io/latest

Your Currency class should be as following:

public class Rates
{
    public double CAD { get; set; }
    public double HKD { get; set; }
    public double ISK { get; set; }
    public double PHP { get; set; }
    public double DKK { get; set; }
    public double HUF { get; set; }
    public double CZK { get; set; }
    public double AUD { get; set; }
    public double RON { get; set; }
    public double SEK { get; set; }
    public double IDR { get; set; }
    public double INR { get; set; }
    public double BRL { get; set; }
    public double RUB { get; set; }
    public double HRK { get; set; }
    public double JPY { get; set; }
    public double THB { get; set; }
    public double CHF { get; set; }
    public double SGD { get; set; }
    public double PLN { get; set; }
    public double BGN { get; set; }
    public double TRY { get; set; }
    public double CNY { get; set; }
    public double NOK { get; set; }
    public double NZD { get; set; }
    public double ZAR { get; set; }
    public double USD { get; set; }
    public double MXN { get; set; }
    public double ILS { get; set; }
    public double GBP { get; set; }
    public double KRW { get; set; }
    public double MYR { get; set; }
}

public class Currency
{
    public Rates rates { get; set; }

}

Your Action Method should be as following:

 public async Task<ActionResult> Index()
        {
            Currency CurencyInfo = new Currency();

            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(Baseurl);

                client.DefaultRequestHeaders.Clear();

                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                Uri myUri = new Uri("https://api.exchangeratesapi.io/latest", UriKind.Absolute);

                HttpResponseMessage Result = await client.GetAsync(myUri);

                if (Result.IsSuccessStatusCode)
                {
                    //Storing the response details recieved from web api   
                    var CurrencyResponse = Result.Content.ReadAsStringAsync().Result;


                    //Deserializing the response recieved from web api and storing into the CurrencyInfo 
                    CurencyInfo = JsonConvert.DeserializeObject<Currency>((JObject.Parse(CurrencyResponse)).ToString());

                }

                //returning the Currency Info to view  
                return View(CurencyInfo);
            }

        }

Note: The class Rates contains all the properties returned by the API. Therefore, you can comment out any of the currencies whose data you do not require. I have tried this code and it works.

在此处输入图像描述

You can use any of the online tools like json2sharp to frame the classes / models for the JSON data you are looking to deserialize.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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