How to convert Json string to C # class object?

I am getting json string in controller, now I want to map this string to C # class object How can I do this?

JSON:

[{"PdID": null, "StName": "435", "DOB": "2015-05-02T17: 09: 35.974Z", "Gender": "5435"}, {"PdID": null "StName ":" 4343 "," DOB ":" 2015-05-02T17: 09: 35.974Z "," Gender ":" 4345 "}]`

my class:

public class PersonDetail
{
    public int PdID { get; set; }
    public int PolicyPurchesID { get; set; }
    public string StName { get; set; }
    public DateTime DOB { get; set; }
    public byte Gender { get; set; }
}

      

Now in my controller I am doing this: -

public ActionResult PolicyDetailAdd(string jsn)
{
    try
    {               
        JavaScriptSerializer objJavascript = new JavaScriptSerializer();

        PersonDetail testModels = (PersonDetail)objJavascript.DeserializeObject(jsn);

        return null;
     }
}

      

I have an exception:

Unable to apply object of type System.Object [] to inject WebApplication1.Models.PersonDetail.

How can I get this string in a list object?

+3


source to share


2 answers


The error occurs because you are trying to deserialize the collection for an object. Also you are using generic Object

. You will need to use



List<PersonDetail> personDetails = objJavascript.Deserialize<List<PersonDetail>>(jsn);

      

+3


source


You have two problems. @Praveen Paulose refers to the first error correctly. But then the object definitions are also wrong regarding JSON.

First the PdId must handle null:

public class PersonDetail
    {
        public int? PdID { get; set; }
        public int PolicyPurchesID { get; set; }
        public string StName { get; set; }
        public System.DateTime DOB { get; set; }
        public byte Gender { get; set; }
    }

      



Secondly, as @Praveen mentioned, JSON returns an array, so you need to handle that.

JavaScriptSerializer objJavascript = new JavaScriptSerializer();

var testModels = objJavascript.DeserializeObject<ICollection<PersonDetail>>(jsn);

      

0


source







All Articles