简体   繁体   中英

How to convert Json string to c# Class object?

I have receive json string in Controller, now i want to map that string in to C# class object How can i do that?

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 have do this:-

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

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

        return null;
     }
}

I got exception in this:

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

How can I get this string into list object?

The error occurs because you are trying to deserialize a collection to an object. Also you are using the generic Object . You will need to use

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

You've got two issues. @Praveen Paulose is correct about the first error. But then object definitions are also incorrect relative to the JSON.

First, PdId needs to 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; }
    }

Second, as @Praveen mentioned, the JSON is returning an array so you need to handle that.

JavaScriptSerializer objJavascript = new JavaScriptSerializer();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM