12

I am new in Xamarin Forms and I am trying to create a method that requests a list of items from an API. However, I am not able to compile the solution due to the error message

"Cannot Convert From String to NewtonSoft.Json.JsonReader" in the line var Items = JsonSerializer.Deserialize<Dictionary<string, Paises>>(content);

Here is the entire routine:

public static async Task<List<Paises>> GetPaisesActivosAsync()
{
    string baseUri = new BaseUri().baseUri;
    string sufixUri = "/PaisesApi/GetActives";
    var uri = baseUri + sufixUri;

    List<Paises> listaPaisesActivos = null;

    HttpResponseMessage response = await client.GetAsync(uri);
    if (response.IsSuccessStatusCode)
    {
        string content = await response.Content.ReadAsStringAsync();
        var Items = JsonSerializer.Deserialize<Dictionary<string, Paises>>(content);
    }
    return listaPaisesActivos;
}    

Thanks in advance for your support.

Regards,

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Henry
  • 167
  • 1
  • 1
  • 8

2 Answers2

24

Use JsonConvert.DeserializeObject() instead. I was having the same issue on C#. The error should disappear after using JsonConvert instead of JsonSerializer.

Salahuddin Ahmed
  • 4,854
  • 4
  • 14
  • 35
sahel
  • 241
  • 1
  • 2
15

Try

using System.Text.Json;

instead of

using Newtonsoft.Json;
luisantruiz
  • 201
  • 3
  • 10
  • 2
    Presumably, they're using NewtonSoft. Asking them to convert to an entirely different serializer without additional instruction isn't especially useful. There may well be benefits to using `System.Text.Json`, but that doesn't answer their specific question about NewtonSoft. – Jeremy Caney Nov 09 '21 at 00:46
  • Note that you can not use both libraries at the same time, since it will give you CS0104 compile error, It would say reference (which is JsonSerializer in this case) is an ambiguous reference between 'identifier' and 'identifier'. Here is the link for more on this https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0104?f1url=%3FappId%3Droslyn%26k%3Dk(CS0104) – Kara Kartal Feb 18 '23 at 18:42