Solved Error: Cannot Convert From String to NewtonSoft.Json.JsonReader


If you getting the error "Cannot Convert From String to NewtonSoft.Json.JsonReader" in Xamarin Forms, we need to address the issue related to JSON parsing in our application, error typically occurs when there is a mismatch between the data format and the expected type during JSON deserialization.

To resolve this error, we can follow these steps:

  1. Firstly, ensure that the JSON data being received or processed is valid and correctly formatted. This includes checking for any missing or unexpected fields.Check that the model or class used for deserialization matches the structure of the JSON data. Make sure that property names and types align properly. Make sure the code where JSON deserialization is performed. Ensure that we are using the correct method or library for deserialization. In Xamarin Forms, commonly used libraries for JSON deserialization include Newtonsoft.Json or System.Text.Json.
  2. If using Newtonsoft.Json, ensure that the JSON string is being correctly converted to a JSON reader or JObject before deserialization. Here's an example:
  3.     string jsonString = "{'id': 1, 'name': 'Product A', 'price': 10.99}";
        JsonTextReader reader = new JsonTextReader(new StringReader(jsonString));
        JObject jsonObject = JObject.Load(reader);
    
        // Now deserialize the JSON object
        Product product = jsonObject.ToObject();
        
  4. If using System.Text.Json, ensure that the JSON string is directly deserialized to the target type. 
  5.     string jsonString = "{'id': 1, 'name': 'Product A', 'price': 10.99}";
        Product product = JsonSerializer.Deserialize(jsonString);
        
  6. Finally, thoroughly test the application to ensure that the error has been resolved and that JSON parsing works as expected under various scenarios.

By following these steps and ensuring proper JSON handling in our Xamarin Forms application, we should be able to resolve the "Cannot Convert From String to NewtonSoft.Json.JsonReader" error.

2

After encountering the same issue in my C# code, we found a solution by using JsonConvert.DeserializeObject() instead of JsonSerializer.Deserialize().

using this approach resolved the error we were facing when trying to convert a JSON string to an object.

If the above solutions do not work for you, you can also consider using System.Text.Json instead of Newtonsoft.Json. However, it's important to note that you cannot use both libraries simultaneously, as it will result in a compile error.

Choosing between Newtonsoft.Json and System.Text.Json, factors such as project requirements, compatibility, performance, and familiarity should be considered. Each library has its strengths and may be more suitable depending on the specific context of the project.
3

When worrking with JSON data returned from an HttpClient request, we often need to deserialize it into objects for further processing. Let's assume we're receiving a JSON response containing a list of Employees, each with properties like Id, Name, Department, and Salary.

Make sure install :Newtonsoft.Json is installed via NuGet

Here's how we can convert the JSON string returned from HttpClient to a list of Employee objects:

  using System;
  using System.Net.Http;
  using System.Threading.Tasks;
  using Newtonsoft.Json; // Ensure Newtonsoft.Json is installed via NuGet

  public class Employee
  {
      public int Id { get; set; }
      public string Name { get; set; }
      public string Department { get; set; }
      public decimal Salary { get; set; }
  }

  public class Program
  {
      private static readonly HttpClient httpClient = new HttpClient();

      public static async Task Main(string[] args)
      {
          // Make HTTP request to get JSON string
          string jsonStr = await httpClient.GetStringAsync("http://samplerestapi.com/employees");

          // Deserialize JSON string to list of Employee objects
          List employees = JsonConvert.DeserializeObject>(jsonStr);

          // Now we have a list of Employee object
          foreach (var employee in employees)
          {
              Console.WriteLine($"Id: {employee.Id}, Name: {employee.Name}, Department: {employee.Department}, Salary: {employee.Salary}");
          }
      }
  }
  

In above example, we first make an asynchronous HTTP request using HttpClient to get the JSON string representing the list of employees. Then, we use JsonConvert.DeserializeObject() method from Newtonsoft.Json library to deserialize the JSON string into a list of Employee objects.