将 json 文件反序列化为 c# 列表<对象>但属性不会进入对象

本文关键字:对象 属性 文件 json 反序列化 列表 | 更新日期: 2023-09-27 18:35:39

>我正在尝试将数据从 json 文件获取到我制作的项目对象,如下所示:

public class Project
{  
    public int ID { get; set; }
    public int Client_ID { get; set; }
    public string Name { get; set; }
    public string code { get; set; }
    public bool active { get; set; }
    public bool billable  { get; set; }
    public string bill_by { get; set; }
}

我要反序列化的 json 文件在每个对象中都有 30 多个属性。我在上面制作的对象中只包含了一些。这可能是我不知道的问题?

当我这样做时:

JavaScriptSerializer ser = new JavaScriptSerializer();
List<Project> projectsList = ser.Deserialize<List<Project>>(jsonString);

杰森:

[
  {
    "project": {
      "id": 10060601,
      "client_id": 4233570,
      "name": "arsnealWebsite",
      "code": "",
      "active": true,
      "billable": true,
      "bill_by": "none",
      "hourly_rate": null,
      "budget": null,
      "budget_by": "none",
      "notify_when_over_budget": false,
      "over_budget_notification_percentage": 80,
      "over_budget_notified_at": null,
      "show_budget_to_all": false,
      "created_at": "2016-02-17T18:59:22Z",
      "updated_at": "2016-02-17T19:20:27Z",
      "starts_on": "2016-02-19",
      "ends_on": "2016-02-29",
      "estimate": null,
      "estimate_by": "none",
      "hint_earliest_record_at": "2016-02-17",
      "hint_latest_record_at": "2016-02-17",
      "notes": "",
      "cost_budget": null,
      "cost_budget_include_expenses": false
    }
  }
]   

。该列表是使用 JSON 文件具有的确切对象数量创建的,但 JSON 文件中的属性没有进入我创建的项目对象的属性?JSON 文件中的属性名称和 C# 代码(上面的类)中的属性名称完全相同?为什么属性值不进入项目对象的属性值?

将 json 文件反序列化为 c# 列表<对象>但属性不会进入对象

您忽略了 "project" json 属性。围绕Project属性创建包装类,如下所示:

public class ProjectWrapper
{  
    public Project Project { get; set; }
}

var projectsList = ser.Deserialize<List<ProjectWrapper>>(jsonString)
  .Select(p => p.Project).ToList();

我建议你在对象中使用DataContractjsonSerializer和数据注释。

因此,您的对象需要:

[DataContract]
public class Project
    {  
        [DataMember]
        public int ID { get; set; }
        [DataMember(Name="ClientId")]        
        public int Client_ID { get; set; }
        [DataMember]        
        public string Name { get; set; }
        [DataMember]        
        public string code { get; set; }
        [DataMember]        
        public bool active { get; set; }
        [DataMember]        
        public bool billable  { get; set; }
        [DataMember]        
        public string bill_by { get; set; }
    }

下面是一个序列化示例:

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Project>));
    
string result = string.Empty;
using (MemoryStream ms = new MemoryStream())
{
   try
   {
      serializer.WriteObject(ms, this);
      ms.Position = 0;
      using (StreamReader sr = new StreamReader(ms))
      {
         result = sr.ReadToEnd();
      }
   }
   catch (Exception ex)
   {
      // your exception handling
   }
}

注意:您可以通过数据注释更改输出属性名称,如上例(ClientId)

再见