2014-09-05 7 views
1

내가이 보이는 사람 개체에 대한 간단한 POCO 있습니다DocumentDb의 쿼리 결과를 deserialize해야합니까?

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 데이터베이스에있는 사람들에게 수집을 쿼리 다음과 같은 코드가 있습니다. 나는 Person 객체 내 쿼리에서 오는 JSON 개체를 변환하려면 어떻게

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.

:

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; 
} 

나는이 코드를 실행

, 나는 다음과 같은 오류를 받고 있어요? 내 MVC 응용 프로그램에서 모델 바인더 꽤 좋은 일을하지만이 별도의 클래스 라이브러리에서 실행 중입니다. 이 JSON 객체를 어떻게 변환해야합니까?

+0

'FirstOrDefault()'는 단일 객체 (또는 null)를 반환합니다. 결과를 목록에 할당 할 수 없습니다. –

+0

FirstOrDefault()를 ToList()로 변경했지만 여전히 문제가있는 점을 보았습니다. 이제 ""System.Collections.GenericList ' "형식으로'System.Collections.GenericList '형식을 암시 적으로 변환 할 수 없습니다."오류가 발생합니다. 변환을 어떻게 처리합니까? foreach를 가지고 각 문서를 Person 객체로 변환해야합니까? 나는 그것을 시도했지만 실패했다. – Sam

+0

나는 그것을 얻었다 고 생각한다. foreach 루프를 수행하고 document/json 객체를 내 POCO 클래스로 deserialize해야하는 것처럼 보입니다. 올바른 방법입니까? 그것은 나를 위해 일했지만 더 좋은 방법이 없는지 확인하고 싶습니다. – Sam

답변

4

이것은 내가 한 것이며 작동합니다. 더 좋은 방법이 있다면 다른 답변도 부탁드립니다.

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; 
} 
+0

내가 찾은 최고의 물건. 나는 수십개의 다른 방식으로 연주했고 아무 것도 일하지 못했습니다. – ThinkingStiff

4

안토니 추 (Anthony Chu) 간단한 해결책은 다음과 같습니다.

private async static Task<List<Person>> GetPeopleList(string colSelfLink) 
{ 
    return client.CreateDocumentQuery<Person>(colSelfLink, "SELECT * FROM People").ToList(); 
} 

이렇게하면 반환 된 각 레코드가 자동으로 deserialize되어 People 객체로 변환됩니다.

+0

컬렉션에 문서 형식이 여러 개인 경우 어떻게해야합니까? 전적으로 우주에서 db 콜렉션은 본질적으로 문서의 "버켓"이라고 할 수 있습니다. – m1nkeh

0

나는이 똑같은 문제가 있었는데, 내 개체 목록이 실패하고 다른 개체 (문서)에 중첩되어있었습니다.

[JsonProperty(PropertyName = "yourPropertyName")] 
:

당신이 문서에 복잡한 객체의 목록이있는 경우

, 복잡한 객체의 속성에 넣어 :

public List<MyObject> MyProperty { get; set; } 

지금은 내가 해결책을 찾아 너무 행복 해요

이것은 주 객체 (document)에서 필요하다고 잘 알려져 있으며, 목록에있을 때까지 중첩 된 객체에는 필요하지 않습니다.