我有一個簡單的POCO的人對象,看起來像這樣:我是否需要反序列化DocumentDb的查詢結果?
public class Person
{
public int PersonId {get; set;}
public string FirstName {get; set;}
public string MiddleName {get; set;}
public string LastName {get; set;}
public char Gender {get; set;}
}
我有以下的代碼,查詢人收藏在我的DocumentDb數據庫。
private async static Task<List<Person>> GetPeopleList(string colSelfLink)
{
dynamic doc = client.CreateDocumentQuery<Document>(colSelfLink, "SELECT p.PersonId, p.FirstName, p.MiddleName, p.LastName, p.Gender FROM People p").AsEnumerable().FirstOrDefault();
List<Person> peopleList = new List<Person>();
if (doc != null)
{
peopleList = doc;
}
return peopleList;
}
當我運行這段代碼,我發現了以下錯誤:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[MyApp.Person]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'PersonId', line 1, position 48.
如何轉換來自我的查詢來一個Person對象的JSON對象?在我的MVC應用程序中,模型聯編程序做得非常好,但它運行在單獨的類庫中。我應該如何轉換這個JSON對象?
'FirstOrDefault()'返回單個對象(或null)。其結果不能分配給列表。 – 2014-09-05 06:01:23
我明白你的觀點,所以我將FirstOrDefault()更改爲ToList(),但仍然存在問題。我現在得到「不能隱式轉換類型'System.Collections.GenericList'到'System.Collections.GenericList '」錯誤。 如何處理轉換?我是否需要使用foreach並將每個文檔轉換爲Person對象?我也嘗試過,但失敗了。 –
Sam
2014-09-05 15:15:01
我想我明白了。看起來我需要做一個foreach循環,並將文檔/ json對象反序列化到我的POCO類中。 這是正確的方法嗎?它爲我工作,但我想確保沒有更好的方法來做到這一點。 – Sam 2014-09-05 15:20:07