对象数组我有一个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
呀,完美的作品,我更喜欢你的方法在@Sachin只是因为我不不喜欢创建包装类:o – r3plica