0

I'm having an issue with converting a one part of a JSON string to C# List. The original code didn't have the [JsonProperty] and it that's where the issue started. I added the [JsonProperty] to the MdId value, but the issue is still happens.

C# Class

public class PendingPatientDocumentRecord
{
    public int PatientDocumentFileMapId;
    public short ContextTypeId;
    public string PatientVisitId;
    public List<string> BillingIds;
    public DateTime? DateOfService;

    [JsonProperty("MdId")]
    public List<string> MdId;
}

Deserialization code

List<PendingPatientDocumentRecord> pendingDocuments = JsonConvert.DeserializeObject<List<PendingPatientDocumentRecord>>(pendingDocumentsJson);

JSON String:

[
  {
    "PatientDocumentFileMapId":12,
    "ContextTypeId":3,
    "DateOfService":"08/31/2022",
    "MdId":"ala"
  }
]

Error:

Error converting value "ala" to type System.Collections.Generic.List`1[System.String]'. Path '[0].MdId'

dbc
  • 104,963
  • 20
  • 228
  • 340
bluesky
  • 624
  • 2
  • 14
  • 25
  • 2
    You json property is of string type, not an array, change the C# class accordingly. – Guru Stron Aug 31 '22 at 18:03
  • Pleas re-read [mre] guidance on posting code and update question to show smaller version of code plus clarify what exactly you want to achieve - whether to read JSON as is or fix JSON to match your class or "read single value as an array". Also consider showing that none of the existing questions helped with that... – Alexei Levenkov Aug 31 '22 at 18:17
  • 4
    In your JSON, the value of `"MdId"` is a string not an array of strings: `"MdId":"ala"`. Is the value always a single string, or is it sometimes a single string, and sometimes an array of strings? If `"MdId"` is sometimes an array but sometimes a single value, this question is a duplicate of [How to handle both a single item and an array for the same property using JSON.net](https://stackoverflow.com/q/18994685/3744182). – dbc Aug 31 '22 at 18:29

1 Answers1

2

MdId needs to be an array so that it can be converted to a list. You don't need the JsonProperty attribute.

  {
    "PatientDocumentFileMapId": 12,
    "ContextTypeId": 3,
    "DateOfService": "08/31/2022",
    "MdId": ["ala"]
  }
Jamie Ide
  • 48,427
  • 16
  • 81
  • 117