0

I m trying to populate class object from excel.I received values in json which i m deserializing but i dont want to get List because in handler class there is function that is of type policy how i can map PolicyNew to class object without List.

var json = JsonConvert.SerializeObject(query);                    
var policynew = JsonConvert.DeserializeObject<List<PolicyNew>>(json);
Policy policy = Handler.GeneratePolicy(policynew);

//Handler.cs
Handler.GeneratePolicy(PolicyNew policynew)
{
}
  • Can you give a sample of your json ? Besides, this might help :https://stackoverflow.com/a/48023576/4180382 – Ole EH Dufour Jun 28 '18 at 11:18
  • Json is coming from var query = from DbDataRecord row in rdr select new { policynumber=row[0]; //------- }; – user10003750 Jun 28 '18 at 11:22
  • it depends on your JSON object if it is an array so it must be mapped to list, if it is only an object you don't use List<>.you can provide example for your json object which will make your question more clear – Hany Habib Jun 28 '18 at 11:25
  • [{\"Carrier\":\"text\",\"PolicyNumber\":\"AB00012345\",\"Transac\":\"XYZ\",.... @ Hany Habib – user10003750 Jun 28 '18 at 11:36

1 Answers1

0

If your jsonstring contains an array, you have to deserialize to some sort of List/Array. If you know, you will only need a single element of that list (or you know, that list only contains one element) you can just take the first element of the resulting list.

var policynew = JsonConvert.DeserializeObject<List<PolicyNew>>(json).FirstOrDefault();

If you have control over the generation of the json string, you could change the serialization and not create an array [{"p1": 3, ...}] but a single object {"p1": 3, ...}

derpirscher
  • 14,418
  • 3
  • 18
  • 35