-1

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

this is the service to get Patient

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

Changed the Get type, to try to match the json

    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 ;
            
        }
suna ali
  • 11
  • 5
  • 1
    Need more info about the crash. Look in VS Output pane - does it say what exception occurred? Maybe a stack trace? Also, put a breakpoint at start of method that crashes, and step through it - which line causes the exception/crash? – ToolmakerSteve Apr 16 '22 at 20:27
  • there is no output in VS – suna ali Apr 16 '22 at 20:38
  • at first,the application is open,but when i add a Patient to firebase ,it work but the application then stopped and crach ,this the problem – suna ali Apr 16 '22 at 21:04
  • Sorry, I didn't notice your comment will, I Turn on all"Common Language Runtime Exceptions", what do you mean by "popup"? – suna ali Apr 16 '22 at 21:34
  • I run the code again, but nothing happens and the application stopped (crash) :( – suna ali Apr 16 '22 at 21:40
  • If the application crashes, then there should be information about the crash in VS **Output/Show output from Debug** pane. You need that information, so you can add it to question. Until you have that, its impossible to help you. **You are running Debug build, right?** – ToolmakerSteve Apr 16 '22 at 21:43
  • yes, please check the edit – suna ali Apr 16 '22 at 22:19
  • From the error message, it sounds like somewhere you have ONE Patient, but a LIST OF PATIENTS is expected. Its somewhere that involves JSON - either when writing to Firebase, or when reading back from Firebase. Perhaps `PatientServices Addpat`. Breakpoint start of that, and step through each line until it crashes. Then compare the code to what's in firebase - is something expecting a list of patients? – ToolmakerSteve Apr 16 '22 at 22:52
  • which **specific line** causes the exception? – Jason Apr 16 '22 at 23:26
  • `await patientService.Addpat(pat);` from debug – suna ali Apr 16 '22 at 23:50
  • that is **your code**. Which line in that method causes the exception? – Jason Apr 17 '22 at 00:01
  • the exception appear at the first when i run the code – suna ali Apr 17 '22 at 00:10
  • So you are saying that the first line of `Addpat` causes the exception? There are three distinct operations on that line - `new Patient(patient)`, `Child` and `PostAsync`. Now you need to figure out which one causes the exception. Try breaking up each operation into its own line. And what is the purpose of `new Patient(patient)`? Why are you creating another instance of `Patient` when you already have one? – Jason Apr 17 '22 at 00:28
  • i found the specific line,please check the edits:( – suna ali Apr 17 '22 at 13:21
  • 1
    Pls check this FYR 1 - https://stackoverflow.com/questions/5979434/deserializing-json-array-into-strongly-typed-net-object & 2 - https://stackoverflow.com/questions/22557559/cannot-deserialize-the-json-array-e-g-1-2-3-into-type-because-type-requ – kaarthick raman Apr 17 '22 at 14:28

1 Answers1

1

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 ---

ToolmakerSteve
  • 18,547
  • 14
  • 94
  • 196
  • please check the question again, I post the photos – suna ali Apr 17 '22 at 19:39
  • sorry, I'm new to Xamarin and I do not know all this information, I try to learn it :( – suna ali Apr 17 '22 at 19:49
  • ,Please check the edits – suna ali Apr 17 '22 at 23:56
  • **this is the git mothed** ``` public static async Task> GetUserPatients() { var url = await firebaseClient .Child($"Specalists/406707265/Patients").BuildUrlAsync(); var result = await Helper.Get>(url); return result ; } ``` – suna ali Apr 18 '22 at 01:47
  • I try your soluation but it give the same ex on ``` return JsonConvert.DeserializeObject(json);``` – suna ali Apr 18 '22 at 01:50
  • done,please check – suna ali Apr 18 '22 at 02:32
  • I edit it ,same like what you say – suna ali Apr 18 '22 at 02:56
  • when I put your solution, the application did not open :( – suna ali Apr 18 '22 at 03:06
  • it gives me the same expectation – suna ali Apr 18 '22 at 03:08
  • Does the exception still say `... into type 'System.Collections.Generic.List'1[CCSN.Models.Patient]' ...`, or does it now give a different type after "into type"? If different, what type does it say now? – ToolmakerSteve Apr 18 '22 at 14:36
  • yes, the same as the question – suna ali Apr 18 '22 at 16:51
  • Are you sure it is **exactly** the same message? If it says `... into type 'System.Collections.Generic.List'1[CCSN.Models.Patient]'`, then it must be code somewhere else that is using `json`. The code I suggested, if it gave that error, would say `... into type 'System.Collections.Generic.Dictionary'1[String, CCSN.Models.Patent] ...`. Do you have any other places that refer to `json` and `List`? – ToolmakerSteve Apr 18 '22 at 17:44
  • ```...'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,CCSN.Models.Patient]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.``` – suna ali Apr 24 '22 at 04:32
  • Ok, Dictionary did not help. Go back to your original code that used `Get>`. I recommend getting some firebase example to work. Then gradually change the example until it does what you need. Google `firebase database xamarin work with list`. Perhaps https://www.c-sharpcorner.com/article/xamarin-forms-working-with-firebase-realtime-database-crud-operations/. – ToolmakerSteve Apr 24 '22 at 16:29