Unable to get Web API result - Cannot deserialize the current JSON object RRS feed

  • Question

  • Hi,

    I am trying to use Web API for the first time and created my Web API, the output is shown correctly in my browse as you can see in below screenshot but when I try to read the data in my WinForm app I get this error:

    Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WindowsFormsApp1.Form1+NewsArticles]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

    Here is my code:

    private async void Button7_Click(object sender, EventArgs e)
        var client = new HttpClient();
        client.BaseAddress = new Uri("https://localhost:44399/api/News");
        var content = new FormUrlEncodedContent(new[]
            new KeyValuePair<string, string>("language", "EN")
        var response = await client.PostAsync("https://localhost:44399/api/News", content);
        var data = await response.Content.ReadAsStringAsync();
        var result = JsonConvert.DeserializeObject<List<NewsArticles>>(data);
        ObservableCollection<NewsArticles> trends = new ObservableCollection<NewsArticles>(result);

    and this is my GET in my Web API:

    // GET: api/News
    public IEnumerable<News> GetNews()
        SqlConnection sql_connection = new SqlConnection("Server=jeccddb.dyndns-office.com; Database=jafaria; User Id=sa; Password=Admin123@;");
        SqlCommand sql_command = new SqlCommand("sp_populate_news", sql_connection);
        sql_command.CommandType = CommandType.StoredProcedure;
        SqlDataReader sql_reader = sql_command.ExecuteReader();
        // ObservableCollection<object> trends = new ObservableCollection<object>();
        List<News> model = new List<News>();
        while (sql_reader.Read())
            News data1 = new News()
                news_id = Convert.ToInt32(sql_reader["news_id"]),
                news_guid = Convert.ToString(sql_reader["news_guid"]),
                news_title = Convert.ToString(sql_reader["news_title"]),
                main_photo = Convert.ToString(sql_reader["main_photo"]),
                news_date = Convert.ToDateTime(sql_reader["news_date"])
        return model;



    Saturday, July 20, 2019 4:58 PM

All replies

  • It looks like you doing a PostAsync to a HttpGet method.  I would use GetAsync instead.   I do not see what the post is returning
    var response = await client.GetAsync("https://localhost:44399/api/News", content);

    Sunday, July 21, 2019 10:28 AM