2013-10-07 42 views
1

对象数组我有一个POCO类看起来像这样:json.net Deserialise到c#

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

资产看起来像这样:

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文件,看起来像这样:

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

最后我有我的代码,看起来像thi 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()); 

只需更换第二sr.ReadToEnd()text,它应该工作:

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

另外,正如@Sachin指出的那样,您的json代表一个对象,其名称为Items,它是一个数组或列表Item对象。
因此,你应该通过一个中间类,如图@萨钦的答案,或者使用字典,像这样:

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

呀,完美的作品,我更喜欢你的方法在@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