skip to Main Content

Need to de-serialize an array of array response to List<Model>

This is my response from other endpoint:

"[[{"BillRateCardId":6992,"ExternalRateCardId":"cd77d9b5-a00e-4696"}]]"

Am using the below line of code to deserialize it to the Model but receiving the error "cant de-serialize that":

List<Model> Res = JsonConvert.DeserializeObject<List<Model>>(Response);

2

Answers


  1. You need to specify the data type that List is expected to contain, either by modeling it as an object:

    using Newtonsoft.Json;
    var input = "[[{"BillRateCardId":6992,"ExternalRateCardId":"cd77d9b5-a00e-4696"}]]";
    var deserialized = JsonConvert.DeserializeObject<List<List<ResponseModel>>>(input);
    class ResponseModel
    {
        public int BillRateCardId { get; set; }
        public string? ExternalRateCardId { get; set; }
    }
    

    or by using dynamic, but then you lose static type checking:

    using Newtonsoft.Json;
    
    var input = "[[{"BillRateCardId":6992,"ExternalRateCardId":"cd77d9b5-a00e-4696"}]]";
    var deserialized = JsonConvert.DeserializeObject<List<List<dynamic>>>(input);
    
    Console.WriteLine(JsonConvert.SerializeObject(deserialized));
    
    Login or Signup to reply.
  2. since you have only one value, you don’t need the custom class

    var data =  JArray.Parse(Response);
        
    long billRateCardId = data.SelectMany(x=>x)
    .Where(x =>(string) x["ExternalRateCardId"]=="cd77d9b5-a00e-4696")
    .Select(x=>(long) x["BillRateCardId"]).FirstOrDefault();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search