将json文件反序列化为c#list <object>,但是这些属性不会进入该对象

时间:2016-02-22 15:50:38

标签: c# json json-deserialization

我正在尝试将数据从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);

JSON:

[
  {
    "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#代码(上面的类)中的属性名称完全相同?为什么属性值不会进入项目对象的属性值?

2 个答案:

答案 0 :(得分:2)

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

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


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

答案 1 :(得分:1)

我建议您在对象中使用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)

再见