[英]Create JSON multi-level with Json.NET in c#
我有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",
}
}
]
問題可能是一些班級成員是私人的。 剛測過:
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);
工作正常。
Department
應該包含一個IEnumerable<Employee>
而不僅僅是一個Employee
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.