如何将Json字符串转换为c#类对象? [英] How to convert Json string to c# Class object?
问题描述
我已经在Controller中收到json字符串,现在我想将该字符串映射到C#类对象中 我该怎么办?
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"}]`
[{"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"}]`
我的课:
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;
}
}
我在这方面有例外:
无法转换类型为System.Object []的对象来键入WebApplication1.Models.PersonDetail.
Unable to cast object of type System.Object[] to type WebApplication1.Models.PersonDetail.
如何将这个字符串放入列表对象?
How can I get this string into list object?
推荐答案
发生此错误是因为您试图将一个集合反序列化为一个对象.另外,您正在使用通用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);
这篇关于如何将Json字符串转换为c#类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!