Home > Mobile >  Need to deserialize an array of arrays in C#
Need to deserialize an array of arrays in C#

Time:09-19

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

CodePudding user response:

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

CodePudding user response:

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();
  • Related