2013-10-07 3 views
1

C 객체의 배열에 나는이처럼 보이는 POCO 클래스가 :json.net Deserialise #

public enum AssetType 
{ 
    Image = 1, 
    Video, 
    Website 
} 

public class Asset 
{  

    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Filename { get; set; } 
    public AssetType Type { get; set; } 
    public string CreatedById { get; set; } 
    public string ModifiedById { get; set; } 
    [Display(Name="Created by")] public string CreatedBy { get; set; } 
    [Display(Name="Modified by")] public string ModifiedBy { get; set; } 
} 

다음 나는 JSON이 있습니다

public class Item : Asset 
{ 
    public int PlaylistId { get; set; } 
    public int AssetId { get; set; } 
    public double Duration { get; set; } 
    public int Order { get; set; } 
} 

자산은 다음과 같습니다 파일은 다음과 같습니다 :

{ 
    "Items":[ 
     { 
     "PlaylistId":1, 
     "Type":2, 
     "Duration":19, 
     "Filename":"stream1_mpeg4.avi" 
     }, 
     { 
     "PlaylistId":1, 
     "Type":2, 
     "Duration":21, 
     "Filename":"stream2_mpeg4.avi" 
     } 
    ] 
} 

마지막으로 나는 S :

public IList<Item> GetAll() 
{ 
    if (File.Exists(itemsPath)) 
    { 
     using (var fs = new FileStream(itemsPath, FileMode.Open)) 
     using (var sr = new StreamReader(fs)) 
     { 
      var text = sr.ReadToEnd(); 
      var array = JsonConvert.DeserializeObject<Item[]>(sr.ReadToEnd()); 
      return array.ToList(); 
     } 
    } 
    else 
     throw new FileNotFoundException("Unable to find the playlist, please make sure that " + itemsPath + " exists."); 
} 

텍스트 변수가 내가 예상하는대로 올바른 JSON 문자열을 포함하지만, 배열 따라서, array.ToList()널; 오류가 발생합니다. 누구든지 내가 뭘 잘못하고 있는지 알아? 사전 /r3plica

답변

3

당신은 두 번 ReadToEnd()를 호출하고, 그래서 두 번째 스트림에서 읽을 더 이상 텍스트가 없습니다 :

var text = sr.ReadToEnd(); 
var array = JsonConvert.DeserializeObject<Item[]>(sr.ReadToEnd()); 

그냥 text와 두 번째 sr.ReadToEnd()를 교체하고 작동해야합니다

var array = JsonConvert.DeserializeObject<Item[]>(text); 

또한 @Sachin에서 올바르게 지적한대로 json은 Items이라는 속성 (Item 개체의 배열 또는 목록)이라는 개체를 나타냅니다. '

var dict = JsonConvert.DeserializeObject<Dictionary<string,Item[]>>(text); 
var array = dict["Items"]; 
+0

그래, 완벽하게 작동하고 나는 단순히 내가 돈 때문에 @Sachin에 당신의 방법을 선호 :
따라서 Sachin의 대답 @에 표시, 또는 대안과 같이 사전을 사용하여 같은 중간 클래스를 통과해야한다 래퍼 클래스를 만드는 것 : o – r3plica

2

당신 json string에서

건배의 특성으로 List<Item>을 가진 개체의 직렬화를 나타냅니다. 즉,이 문자열을 List<Item>을 속성으로 갖는 객체로 역 직렬화해야 함을 의미합니다. 그래서 당신은이

public class Wrapper 
{ 
    public List<Item> items { get; set; } 
} 

같은 래퍼 클래스를 만들 수 있습니다 다음 지금 당신은 당신의 배열이 즉, 내부에 두 개의 요소를 가지고 볼 수있는이

var array = JsonConvert.DeserializeObject<Wrapper>(text); 

처럼 역 직렬화. array.Count=2