Search code examples
c#jsonjson-deserialization

Deserialize json file to c# list<object> but the properies won't come into the object


I am trying to get data from a json file to a project object that I have made that looks like this:

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; }
}

The json file that I want to deserialize has over 30 properties in each object. I have only included a few in the object I have made above. That might be the problem I don't know?

When I do this:

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

... the list gets created with the exact amount of objects that the json file have but the properties in the json file doesn't come into the properties of my project object I have created? the name of the properties in the json file and the name of the properties in the c# code(the class above) are exactly the same? How come the properties value doesn't go into the properties value of the project object?


Solution

  • You're ignoring the "project" json property. Create wrapper class around Project property like:

    public class ProjectWrapper
    {  
        public Project Project { get; set; }
    }
    
    
    var projectsList = ser.Deserialize<List<ProjectWrapper>>(jsonString)
      .Select(p => p.Project).ToList();