다음과 같은 POCO 클래스가 있습니다.
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"
}
]
}
마지막으로 다음과 같은 코드가 있습니다.
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 문자열을 포함하지만, 배열은 널 (null), 그러므로 array.ToList () ; 오류가 발생합니다. 내가 뭘 잘못하고 있는지 아는 사람이 있습니까?
미리 건배 / r3plica
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
.
따라서 @Sachin의 답변에 표시된대로 중간 클래스를 통과하거나 다음과 같이 사전을 사용해야합니다.
var dict = JsonConvert.DeserializeObject<Dictionary<string,Item[]>>(text);
var array = dict["Items"];
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다