我有一个简单的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