无法反序列化JSON数组

时间:2017-01-26 16:55:10

标签: c# linq json.net

以下是我的课程:

public class Employee : Base
{
    public int Id { get; set; }
    public string Fname { get; set; } 
    public DepartmentModel Department { get; set; }
}

public class DepartmentModel : Base
{
    public int Id { get; set; }
    public string DepartmentName { get; set; }
    public List<Location> Locations { get; set; }
}

public class Locations
{
    public string Area { get; set; }
    public string StreetNo { get; set; }
    public string Nearby { get; set; }
}

服务回复:

var response = new
{
    id = 100,
    department = new
    {
        id = 200,
        departmentName = "Abc",
        locations = new[]
        {
            Employee.Department.Locations
                    .Select
                    (
                        lo => new
                        {
                             area = lo.Area,
                             streetNo = lo.streetNo,
                             nearby = lo.Nearby
                        }
                    ).ToList()
        }
    }
};

return JsonConvert.SerializeObject(response);

现在,当我尝试将上面的JSON反序列化到我的类Employee中时,如下所示:

var deserialize = JsonConvert.DeserializeObject<Employee>(response.ToString());

错误:

enter image description here

如何在JSON上面反序列化?

3 个答案:

答案 0 :(得分:3)

问题在于:

locations = new[]
            {
                Employee.Department.Locations
                        .Select
                        (
                            lo => new
                            {
                                area = lo.Area,
                                streetNo = lo.streetNo,
                                nearby = lo.Nearby
                            }
                        ).ToList()
            }

LINQ表达式以.ToList()结尾,因此已经返回了一个项目列表。然后,您将new[]包装在数组中。因此,JSON不是Location的数组,而是 Location数组的数组。

答案 1 :(得分:1)

尝试删除new[]。您不希望位置是列表数组

locations = Employee.Department.Locations
                               .Select(lo => new
                                           {
                                                 area = lo.Area,
                                                 streetNo = lo.streetNo,
                                                 nearby = lo.Nearby
                                            }
                                        ).ToList()

答案 2 :(得分:1)

您需要实例化nodes并使用与类相同的外壳:

new Employee()