Reputation:
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?
Upvotes: 3
Views: 1086
Reputation: 7484
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);
Upvotes: 0
Reputation: 5771
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);
Upvotes: 3