c# - 如何将 Json 字符串转换为 C# Class 对象?

标签 c# json model-view-controller

我在 Controller 中收到了 json 字符串,现在我想将该字符串映射到 C# 类对象 我该怎么做?

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"}]`

我的类(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; }
}

现在在我的 Controller 中我已经这样做了:-

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

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

        return null;
     }
}

我在这方面有异常(exception):

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

如何将这个字符串放入列表对象中?

最佳答案

错误发生是因为您试图将集合反序列化为对象。您还使用了通用 Object。您将需要使用

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

关于c# - 如何将 Json 字符串转换为 C# Class 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30005332/

相关文章:

c# - UWP 中带有 3 个以上按钮的自定义内容对话框

从 ASP.NET MVC 返回 null 时,jQuery post JSON 失败

iOS MVC 实现

ruby-on-rails - (MVC) 跨越多个模型的逻辑

c# - 建筑问题: solutions sharing same class libraries; project promotion; forking solutions

c# - 如何处理使用 CsvHelper 解析时的空列?

c# - ExecuteScalar() 总是返回 NULL

Java Reflection - 获取类的所有实例变量名

json - 非常奇怪的 Cordova/Phonegap JSON 错误 : Unexpected token in JSON at position 0

model-view-controller - 如何分别观察一个界面的不同概念?