json.net Deserialise to array of objects c# -


i have poco class looks this:

public class item : asset {     public int playlistid { get; set; }     public int assetid { get; set; }     public double duration { get; set; }     public int order { get; set; } } 

and asset looks this:

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

and have json file looks this:

{    "items":[       {          "playlistid":1,          "type":2,          "duration":19,          "filename":"stream1_mpeg4.avi"       },       {          "playlistid":1,          "type":2,          "duration":21,          "filename":"stream2_mpeg4.avi"       }    ] } 

and have code looks this:

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 find playlist, please make sure " + itemspath + " exists."); } 

the text variable contains correct json string expect, array null, therefore array.tolist(); throws error. know doing wrong?

cheers in advance /r3plica

you're calling readtoend() twice, second time there's no more text read on stream:

var text = sr.readtoend(); var array = jsonconvert.deserializeobject<item[]>(sr.readtoend()); 

just replace second sr.readtoend() text , should work:

var array = jsonconvert.deserializeobject<item[]>(text); 

also, correctly pointed out @sachin, json represent object property called items array or list of item objects.
therefore, should pass through intermediate class shown in @sachin's answer, or alternatively using dictionary, this:

var dict = jsonconvert.deserializeobject<dictionary<string,item[]>>(text); var array = dict["items"]; 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -

php - Accessing static methods using newly created $obj or using class Name -