1
我有我從API得到以下JSON結構:查詢使用LINQ查詢嵌套對象與加盟
{
"event_instance": [
{
"id": 55551244,
"event_id": 11112,
"name": "Brown Belt Karate Class",
"staff_members": [
{
"id": 12345,
"name": "John Smith"
}
],
"people": [
{
"id": 111,
"name": "Jane Doe"
},
{
"id": 222,
"name": "Josh Smith"
},
{
"id": 333,
"name": "Ben Johnson"
}
],
"visits": [
{
"id": 1234578,
"person_id": 111,
"state": "completed",
"status": "complete"
},
{
"id": 1239865,
"person_id": 222,
"state": "completed",
"status": "complete"
},
{
"id": 1239865,
"person_id": 333,
"state": "canceled",
"status": "cancel"
}
]
}
]
}
我使用JSON.NET反序列化到下面的.NET對象是:
[JsonObjectAttribute("event_instance")]
public class EventInstance
{
[JsonPropertyAttribute("id")]
public int Id { get; set; }
[JsonPropertyAttribute("event_id")]
public int EventId { get; set; }
[JsonPropertyAttribute("name")]
public string Name { get; set; }
[JsonPropertyAttribute("staff_members")]
public List<StaffMember> StaffMembers { get; set; }
[JsonPropertyAttribute("visits")]
public List<Visit> Visits { get; set; }
[JsonPropertyAttribute("people")]
public List<Student> Students { get; set; }
}
[JsonObjectAttribute("staff_members")]
public class StaffMember
{
[JsonPropertyAttribute("id")]
public int Id { get; set; }
[JsonPropertyAttribute("name")]
public string Name { get; set; }
}
[JsonObjectAttribute("people")]
public class People
{
[JsonPropertyAttribute("id")]
public int Id { get; set; }
[JsonPropertyAttribute("name")]
public string Name { get; set; }
}
[JsonObjectAttribute("visits")]
public class Visits
{
[JsonPropertyAttribute("id")]
public int Id { get; set; }
[JsonPropertyAttribute("person_id")]
public int PersonId { get; set; }
[JsonPropertyAttribute("state")]
public string State { get; set; }
[JsonPropertyAttribute("status")]
public string Status { get; set; }
}
我使用下面的代碼反序列化:
var event = (EventInstance)JsonConvert.DeserializeObject(json, typeof(EventInstance));
以上工作正常,並給了我上述json結構的精確對象表示。現在我試圖查詢這個事件對象來過濾/項目到一個新的結構,然後我可以序列化回json併發送到瀏覽器。我需要返回處於「已完成」狀態和「完成」狀態的活動的學生列表。正如你所看到的,people數組綁定到訪問數組(使用id和person_id)。我想產生以下簡單的輸出:
- 11112,棕帶空手道班,約翰·史密斯,111,李四
- 11112,棕帶空手道班,約翰·史密斯,222,約什 - 史密斯
我已經試過這樣的事情:
var studentList = from theClass in event
from staff in theClass.StaffMembers
from student in theClass.People
from visits in theClass.Visits
where visits.Status == "complete"
&& visits.State == "completed"
select new
{
event_id = theClass.EventId
class_name = theClass.Name,
instructor_name = staff.Name,
student_id = student.Id,
student_name = student.Name
};
string _data = JsonConvert.SerializeObject(studentList);
當然,這會產生重複的學生姓名。我是linq新手。基本上,我需要加入/綁定人員並訪問數組,以便爲該ID返回單個學生以及該事件的根數據。任何建議,以更好的方式來做到這一點非常讚賞!
啊,現在是有道理的。 Linq需要一些時間才能習慣。謝謝!! – MattoMK