0

My JSON looks like:

[
  {
    "Key": {
      "PatientName": "Hans Gerd",
      "Alter": 81,
      "Geschlecht": "M",
      "Zimmernummer": 1,
      "PatientenLiegeplatz": 0,
      "IsDummyData": false
    },
    "Value": {
      "Puls": 0,
      "Temperatur": 0.0,
      "Systole": 0,
      "Diastole": 0,
      "DictationText": "",
      "Timestamp": "2021.05.24 12:31:06"
    }
  }
]

Serialization:

string json = JsonConvert.SerializeObject(saveObj.CareRoutineDataDictionary.ToArray(), Formatting.Indented);

How to Deserialize it? I have tried so much and it doesn't work. Common error Messages:

Unexpected character encountered while parsing value

If I try to do:

Dictionary<BasicPatientData, CareRoutineData> data = JsonConvert.DeserializeObject<Dictionary<BasicPatientData, CareRoutineData>>(File.ReadAllText(SaveFilePath));

I get an error:

JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[BasicPatientData,CareRoutineData]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

Can anyone help?

Akshay G
  • 2,070
  • 1
  • 15
  • 33
Xelia
  • 1
  • 2
  • It's not clear what all your types are, also why are you doing `ToArray` when you serialise? – DavidG May 24 '21 at 10:55
  • The toArray is neccessary otherwise the Keys are not serialized, i only get the second of the Dictionary then. – Xelia May 24 '21 at 11:11
  • That isn't true, it will still give you the keys. – DavidG May 24 '21 at 11:17
  • You have a dictionary with **complex keys** that has been serialized as an array. You need to deserialize that as a `List>` and then convert to a dictionary. See [How can I serialize/deserialize a dictionary with custom keys using Json.Net?](https://stackoverflow.com/q/24681873/3744182). Or you could use one of the `JsonConverter` implementations from [Newtonsoft Json Deserialize Dictionary as Key/Value list from DataContractJsonSerializer](https://stackoverflow.com/q/28451990/3744182). In fact this looks to be a duplicate, agree? – dbc May 24 '21 at 13:42
  • `CustomDictionaryConverter` from [this answer](https://stackoverflow.com/a/59310390/3744182) to [How can I serialize/deserialize a dictionary with custom keys using Json.Net?](https://stackoverflow.com/q/24681873/3744182) looks like it might the easiest and most general solution. – dbc May 24 '21 at 13:45

0 Answers0