Home > Software design >  Newtonsoft.Json.JsonSerializationException Message=Cannot deserialize the current JSON object
Newtonsoft.Json.JsonSerializationException Message=Cannot deserialize the current JSON object

Time:04-18

I try to add patient to firebase database.

This is the code

Patient.cs

public class Patient
{
    public string ID { get; set; }
    public string PatientName { get; set; }
    public string PatientGender { get; set; }
    public string PatientAddress { get; set; }
    public string PatientWeight { get; set; }
    public string PatientHeight { get; set; }
    public string PatientMobileNO { get; set; }
    public string PatientBirthday { get; set; }
    public string PatientGenticesDiseses { get; set; }

    // public List<Appoitment> Appointments { get; set; }
    public ObservableCollection<Appoitment> Appointments;

    public Patient()
    {
    }

    public Patient(Patient instans)
    {
        ID = instans.ID;
        PatientName = instans.PatientName;
        PatientGender = instans.PatientGender;
        PatientAddress = instans.PatientAddress;
        PatientWeight = instans.PatientWeight;
        PatientHeight = instans.PatientHeight;
        PatientMobileNO = instans.PatientMobileNO;
        PatientGenticesDiseses = instans.PatientGenticesDiseses;
        Appointments = instans.Appointments;

    }
}

PatientServices.cs

public async Task Addpat( Patient patient)
{
    var x = await firebaseClient
            .Child($"Specalists/406707265/Patients")
            .PostAsync(new Patient(patient));

    Patient pat = new Patient(x.Object);
    pat.ID = x.Key;

    await firebaseClient
        .Child($"Specalists/406707265/Patients/{pat.ID}")
        .PatchAsync(pat);
}

addPatient.xaml.cs

public partial class AddPatientPage : ContentPage
{
    public AddPatientPage()
    {
        InitializeComponent();
        AddPatientClick();
    }

    public async void addPatient()
    {
        PatientService patientService = new PatientService();

        Patient pat = new Patient();
        pat.PatientAddress = PatientAddress.Text;
        pat.PatientBirthday = PatientBirthday.Text;
        pat.PatientGender = PatientGender.Text;
        pat.PatientGenticesDiseses = PatientGenticsDiseses.Text;
        pat.PatientHeight = PatientHeight.Text;
        pat.PatientMobileNO = PatientMobileNo.Text;
        pat.PatientName = PatientName.Text;
        pat.PatientWeight = PatientWeight.Text;

        Random rd = new Random();
        int rand_num = rd.Next(1, 4000);
        pat.ID = rand_num.ToString();

        try
        {
            await patientService.Addpat(pat);
            await Application.Current.MainPage.DisplayAlert("message", "Patient Added", "ok");
            await Navigation.PushAsync(new PatientsListPage());
        }
        catch (Exception ex)
        {
            await Application.Current.MainPage.DisplayAlert("error", ex.Message, "ok");
        }
    }

    void AddPatientClick()
    {
        save.GestureRecognizers.Add(new TapGestureRecognizer()
            {
                Command = new Command(() =>
                {
                    addPatient();
                })
            });
    }
}

addPatient.xaml

<Entry Placeholder="Patient Address"
       x:Name="PatientAddress"></Entry>
<Entry Placeholder="Patient Birthday"
       x:Name="PatientBirthday"></Entry>

<Entry Placeholder="Patient Gender"
       x:Name="PatientGender"></Entry>
<Entry Placeholder="Patient Gentics Diseses"
       x:Name="PatientGenticsDiseses"></Entry>
<Entry Placeholder="Patient Height"
       x:Name="PatientHeight"></Entry>

<Entry Placeholder="Patient Mobile Number"
       x:Name="PatientMobileNo"></Entry>

<Entry Placeholder="Patient Name"
       x:Name="PatientName"></Entry>
<Entry Placeholder="Patient Weight"
       x:Name="PatientWeight"></Entry>

<Label x:Name="save" HorizontalOptions="Center" >Save</Label>

The code works, and the Patient is added to Firebase, but when it gives me the alert the application crash and stopped?

I try to fix it, but I do not know the problem, what should I do?

here the ex

Newtonsoft.Json.JsonSerializationException
  Message=Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[CCSN.Models.Patient]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path '0', line 1, position 5.

in this line to get patient

return JsonConvert.DeserializeObject<TEntity>(json);

  public static async Task<TEntity> Get<TEntity>(string url)
        {
            HttpClientHandler clientHandler = new HttpClientHandler();
            clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };

            HttpClient client = new HttpClient(clientHandler);

            var response = await client.GetAsync(url);
            var json = await response.Content.ReadAsStringAsync();
            
            return JsonConvert.DeserializeObject<TEntity>(json);
        }

is the error from not converting?

and how can i convert to object or json

JSON (pretty-printed)

{
  "0": {
    "Appointments": [
      {
        "AppointmentDate": "2022-04-12T00:00:00 03:00",
        "AppointmentPatientName": "Ghaidaa",
        "AppointmentTime": "00:00:00",
        "FollowUpAddNote": "test",
        "FollowUpDate": "22-2-2022",
        "FollowUpGoals": "R alpha",
        "FollowUpTools": "None",
        "ID": "0",
        "PatientID": "0"
      },
      {
        "AppointmentDate": "2022-04-11T18:58:03.623061 03:00",
        "AppointmentPatientName": "Ghaidaa",
        "FollowUpAddNote": "None",
        "FollowUpDate": "22-2-2022",
        "FollowUpGoals": "R alpha",
        "FollowUpTools": "None",
        "ID": "1",
        "PatientID": "0"
      },
      {
        "AppointmentDate": "2022-04-11T18:58:03.623061 03:00",
        "AppointmentPatientName": "Ghaidaa",
        "FollowUpAddNote": "None",
        "FollowUpDate": "22-2-2022",
        "FollowUpGoals": "R alpha",
        "FollowUpTools": "None",
        "ID": "2",
        "PatientID": "0"
      },
      {
        "AppointmentDate": "2022-04-11T18:58:03.623061 03:00",
        "AppointmentPatientName": "Ghaidaa",
        "FollowUpAddNote": "None",
        "FollowUpDate": "22-2-2022",
        "FollowUpGoals": "R alpha",
        "FollowUpTools": "None",
        "ID": "3",
        "PatientID": "0"
      },
      {
        "AppointmentDate": "2022-04-12T00:00:00 03:00",
        "AppointmentPatientName": "Ghaidaa",
        "AppointmentTime": "00:00:00",
        "FollowUpAddNote": "test",
        "FollowUpDate": "22-2-2022",
        "FollowUpGoals": "R alpha",
        "FollowUpTools": "None",
        "ID": "4",
        "PatientID": "0"
      }
    ],
    "ID": "0",
    "PatientAddress": "Nablus-Tell",
    "PatientBirthday": "8-3-2001",
    "PatientGender": "Female",
    "PatientGenticsDiseses": "None",
    "PatientHeight": 168,
    "PatientMobileNo": "0568982001",
    "PatientName": "Ghaidaa",
    "PatientWeight": 60
  },
  "1": {
    "Appointments": [
      {
        "AppointmentDate": "2022-04-12T18:58:03.623061 03:00",
        "AppointmentPatientName": "Ghaidaa",
        "FollowUpAddNote": "None",
        "FollowUpDate": "22-2-2022",
        "FollowUpGoals": "R alpha",
        "FollowUpTools": "None",
        "ID": "0",
        "PatientID": "1"
      },
      {
        "AppointmentDate": "2022-04-11T18:58:03.623061 03:00",
        "AppointmentPatientName": "Ghaidaa",
        "FollowUpAddNote": "None",
        "FollowUpDate": "22-2-2022",
        "FollowUpGoals": "R alpha",
        "FollowUpTools": "None",
        "ID": "1",
        "PatientID": "0"
      },
      {
        "AppointmentDate": "2022-04-11T18:58:03.623061 03:00",
        "AppointmentPatientName": "Ghaidaa",
        "FollowUpAddNote": "None",
        "FollowUpDate": "22-2-2022",
        "FollowUpGoals": "R alpha",
        "FollowUpTools": "None",
        "ID": "2",
        "PatientID": "0"
      },
      {
        "AppointmentDate": "2022-04-11T18:58:03.623061 03:00",
        "AppointmentPatientName": "Ghaidaa",
        "FollowUpAddNote": "None",
        "FollowUpDate": "22-2-2022",
        "FollowUpGoals": "R alpha",
        "FollowUpTools": "None",
        "ID": "3",
        "PatientID": "0"
      },
      {
        "AppointmentDate": "2022-04-12T18:58:03.623061 03:00",
        "AppointmentPatientName": "Ghaidaa",
        "FollowUpAddNote": "None",
        "FollowUpDate": "22-2-2022",
        "FollowUpGoals": "R alpha",
        "FollowUpTools": "None",
        "ID": "4",
        "PatientID": "0"
      }
    ],
    "ID": "1",
    "PatientAddress": "Nablus-Tell",
    "PatientBirthday": "8-3-2001",
    "PatientGender": "Female",
    "PatientGenticsDiseses": "None",
    "PatientHeight": 168,
    "PatientMobileNo": "0568982001",
    "PatientName": "shada",
    "PatientWeight": 60
  },
  "-N-tZ6hbyPpWOWeoo9o4": {
    "ID": "45455184",
    "PatientAddress": "g",
    "PatientGender": "h",
    "PatientGenticesDiseses": "b",
    "PatientHeight": "26",
    "PatientMobileNO": "hshhs",
    "PatientName": "sgagaga",
    "PatientWeight": "67"
  }
}

stack here

this is the service to get Patient

    public static async Task<IEnumerable<Patient>> GetUserPatients()
        {
            var url = await firebaseClient
                     .Child($"Specalists/406707265/Patients").BuildUrlAsync();
            var patientsDict = await Helper.Get<Dictionary<string, Patient>>(url);
            var result = patientsDict.Values.ToList();
           
            return result ;
            
        }

CodePudding user response:

The back and forth in comments has gotten unwieldy. Here is a community wiki showing the status of resolving this.

Exception:

Newtonsoft.Json.JsonSerializationException
  Message=Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[CCSN.Models.Patient]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path '0', line 1, position 5.

NOTE: Exception says is trying to deserialize into

'System.Collections.Generic.List`1[CCSN.Models.Patient]'

In c# that would be a List<Patient>.

Statement in PatientServices.Addpat in which exception is believed to occur:

        var x = await firebaseClient
                .Child($"Specalists/406707265/Patients")
                .PostAsync(new Patient(patient));

Those statements must lead to this - the lower-level line in which exception occurs:

    return JsonConvert.DeserializeObject<TEntity>(json);

  1. json (skipping most of it):
{
  "0":{
   "Appointments":[
    {"AppointmentDate":"2022-04-12T00:00:00 03:00"
    }
   ],
   "ID": "0",
   "PatientName": "Ghaidaa"
  },

 "-N-tZ6hbyPpWOWeoo9o4": {
   "ID": "45455184",
   "PatientName": "sgagaga"
  }
}
  1. TEntity:

Based on the error message, TEntity is presumably List<Patient>.


The problem is that the json (shown above) isn't in the expected format. It is a dynamic object with keys "0", "1", "-N-tZ6hbyPpWOWeoo9o4".

The calling code is expecting a json array, which would look like this:

[ {
   "Appointments":[
    {"AppointmentDate":"2022-04-12T00:00:00 03:00"
    }
   ],
   "ID": "0",
   "PatientName": "Ghaidaa"
  },

  {
   "ID": "45455184",
   "PatientName": "sgagaga"
  }
]

The difference is easiest to see by examining the beginning and end of the json.


One way to fix is to deserialize to a Dictionary. Then extract the values of the Dictionary into a list.

Find code that looks something like the line below. Replace:

    var patients = await Helper.Get<List<Patient>>(url);

With:

    var patientsDict = await Helper.Get<Dictionary<string, Patient>>(url);
    var patients = patientsDict.Values;

Or depending on how you use it, might change the last line to:

    var patients = patientsDict.Values.ToList();

An ALTERNATIVE way to fix is to change the server side, so that it sends an array of Patients instead of a dynamic object.

--- Making that change is beyond the scope of this answer ---

  • Related