Cannot Convert From String to NewtonSoft.Json.JsonReader
Asked Answered
Y

2

15

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,

Yardley answered 4/8, 2021 at 2:27 Comment(5)
Have a breakpoint at that line and check what's in your "content"Hyracoid
@Yardley What is Paises? "content" is not null?Brahma
Hi @Shaw, the issue is that the error is present in programming time, which does not allow to compile the solutionYardley
Sorry for that. So are you using Newtonsoft.Json, and if so, try JsonConvert.DeserializeObject. Plus, recommended using var instead of string.Hyracoid
use using System.Text.Json; insteadJabe
A
30

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

Apriorism answered 14/8, 2021 at 22:2 Comment(1)
It is all dependent on which library you decide to use. The two choices are System.Text.Json and NewtonSoft.Viminal
K
17

Try

using System.Text.Json;

instead of

using Newtonsoft.Json;
Karakul answered 8/11, 2021 at 22:47 Comment(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.Higinbotham
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 learn.microsoft.com/en-us/dotnet/csharp/misc/…Osis

© 2022 - 2024 — McMap. All rights reserved.