ASP.NET MVC 5 consuming api

0

I am developing a new platform which consumes data from an API of the SBIF, but the JSON with the data that it returns to me comes like this

{
    "Dolares":
    [
        {
            "Valor": "603,31",
            "Fecha": "2018-04-27"
        {
    ]
}

To use it httpClient use and throw me a "deserialize" error I have several techniques that I found in here but none of them works for me. The error that returns the view is this.

  

Can not deserialize the current JSON object (eg {"name": "value"}) into type 'System.Collections.Generic.List'1 [DetamaticWeb.Models.DolarViewModel]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly.   To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from to JSON object.   Path 'Dolares', line 2, position 12.

Would someone be so kind as to tell me how to use this api please?

Controller

string Baseurl = "http://api.sbif.cl/";
        public async Task<ActionResult> Index()
        {
            List<DolarViewModel> EmpInfo = new List<DolarViewModel>();

            using (var client = new HttpClient())
            {
                //Passing service base url  
                client.BaseAddress = new Uri(Baseurl);

                client.DefaultRequestHeaders.Clear();
                //Define request data format  
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                //Sending request to find web api REST service resource GetAllEmployees using HttpClient  
                HttpResponseMessage Res = await client.GetAsync("api");

                //Checking the response is successful or not which is sent using HttpClient  
                if (Res.IsSuccessStatusCode)
                {
                    //Storing the response details recieved from web api   
                    var EmpResponse = Res.Content.ReadAsStringAsync().Result;

                    //Deserializing the response recieved from web api and storing into the Employee list  
                    EmpInfo = JsonConvert.DeserializeObject<List<DolarViewModel>>(EmpResponse);

                }
                //returning the employee list to view  
                return View(EmpInfo);
            }
        }

Model

public class DolarViewModel
{
    public string Valor { get; set; }
    public string Fecha { get; set; }
}

Thank you.

    
asked by vcasas 27.04.2018 в 14:07
source

2 answers

0

According to what I see is that the model is this:

Public Class DolarViewModel{
    public List<ListaValoresDolarViewModel> Dolares {get; set;}
}

Public Class ListaValoresDolarViewModel{
    public string Valor { get; set; }
    public string Fecha { get; set; }
}

And to recover that data would be:

EmpInfo = JsonConvert.DeserializeObject<DolarViewModel>(EmpResponse);

I hope it serves you.

    
answered by 27.04.2018 / 14:37
source
0

You can also pause a dynamic and use it directly at properties or traverse them. It is very useful when we access APIs and we do not have to generate a model for that in our entity layer. Take it as another "lighter" alternative

Example with dynamic:

var jsonData = "{\"Dolares\":[{\"Valor\": \"603,31\",\"Fecha\": \"2018-04-27\"}]}";
        dynamic demo = Newtonsoft.Json.Linq.JObject.Parse(jsonData);

        Console.WriteLine(demo.Dolares[0].Valor);
        Console.WriteLine(demo.Dolares[0].Fecha);

        foreach (var item in demo.Dolares)
        {
            Console.WriteLine(item.Valor);
            Console.WriteLine(item.Fecha);
        }

Which is the same as having (depending on your architecture and what you do with the viewModel that arms) that this code has the "predefined" model

 DolarViewModel demo2 = Newtonsoft.Json.JsonConvert.DeserializeObject<DolarViewModel>(jsonData);
        Console.WriteLine(demo2.Dolares[0].Valor);
        Console.WriteLine(demo2.Dolares[0].Fecha);

        foreach (var item in demo2.Dolares)
        {
            Console.WriteLine(item.Valor);
            Console.WriteLine(item.Fecha);
        }

Assuming the DolarViewModel equals

 public class DolarViewModel
{
    public List<ListaValoresDolarViewModel> Dolares { get; set; }
}

public class ListaValoresDolarViewModel
{
    public string Valor { get; set; }
    public string Fecha { get; set; }
}

Links that can help you

I hope it will help or guide you

    
answered by 01.05.2018 в 22:57