使用c#中的Json.NET创建JSON多级

时间:2012-10-19 05:48:17

标签: c# json json.net

我有2个课程:

class Employee
{
    string name;
    string age;
}

class Departments
{
    string branch;
    Employee A;
}

声明新列表:

List<Departments> lstDp = new List<Departments>();

获取/设置并将员工添加到列表中...我有一个部门列表包括员工信息。然后:

string json = JsonConvert.SerializeObject(lstDp, Newtonsoft.Json.Formatting.Indented);

但输出JSON字符串仅包含元素“branch”。这有什么问题?我希望输出像这样:

[
  {
    "branch": "NY",
    "Employee": {
        "name": "John Smith",
        "age": "29",
    }
  }
]

2 个答案:

答案 0 :(得分:2)

问题可能是某些班级成员是私人的。刚刚测试过:

class Employee
{
    public string Name { get; set; }
    public string Age { get; set; }
}

class Departments
{
    public string Branch { get; set; }
    public Employee Employee { get; set; }
}

var lstDp = new List<Departments> {
            new Departments {
                Branch = "NY",
                Employee = new Employee { Age = "29", Name = "John Smith" }
            }
        };
var json = JsonConvert.SerializeObject(lstDp, Formatting.Indented);

工作正常。

答案 1 :(得分:1)

Department应包含IEnumerable<Employee>,而不仅仅是Employee