gpt4 book ai didi

c# - 我是否需要反序列化来自 DocumentDb 的查询结果?

转载 作者:行者123 更新时间:2023-11-30 19:39:56 24 4
gpt4 key购买 nike

我有一个简单的 person 对象的 POCO,如下所示:

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 数据库中的 People 集合。

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.

如何将来自查询的 JSON 对象转换为 Person 对象?在我的 MVC 应用程序中,模型绑定(bind)器做得很好,但它在单独的类库中运行。我应该如何转换此 JSON 对象?

最佳答案

这就是我所做的并且有效。如果有更好的方法,我会很感激其他答案。

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().ToList();
List<Person> peopleList = new List<Person>();
if (doc != null)
{
Person person;
foreach(var item in doc)
{
person = JsonConvert.DeserializeObject<Person>(item.ToString());
peopleList.Add(person);
}
}
return peopleList;
}

关于c# - 我是否需要反序列化来自 DocumentDb 的查询结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25678167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com