c# - How to Add Data from a litJson save File to List -


what i'm trying add data have saved in litjson file list, , in correct format. can call in game later on, icons. here's code, should easy recreate test problem i'm having.

jsonicons class:

using unityengine; using system.collections; using system.collections.generic;  [system.serializable] public class jsonicons {      public string iconname;//shows icon name in list     public int iconid;// shows icon id in list     public sprite assignicon;      public jsonicons(string name, int id )     {         iconname = name;         iconid = id;     }      public jsonicons()     {     } } 

jsontest class:

using unityengine; using system.collections; using system.collections.generic; using litjson; using system.io;  //this class saving public class jsontest : monobehaviour {      public list<jsonicons> jicon = new list<jsonicons>();     public jsondata jcd;      protected jsonicons kz, testtk;      public void start()     {         testtk = new jsonicons("kagami", 40);         kz = new jsonicons("magic", 0);          jicon.add(testtk); //add things list save         jicon.add(kz);          jcd = jsonmapper.tojson(jicon);         //this saved things inside jicon list json file         file.writealltext(application.datapath + "/jsonsavetest.json", jcd.tostring());         //debug.log(jcd);     } } 

jsonreadtest class:

using unityengine; using system.collections; using system.collections.generic; using system.io; using litjson;  public class jsonreadtest : monobehaviour {      public list<jsonicons> readsj = new list<jsonicons>();      private string jstring;     public jsondata icondata;      // use initialization     void start ()      {         //trying file load in correct format inside readsj list         jstring = file.readalltext(application.datapath + "/jsonfiles/jsonsavetest.json");         icondata = jsonmapper.toobject(jstring);     } } 

you either create class called jsoniconlist, contain list (by way should rename jsonicons jsonicon represents single item). can deserialize jsonmapper class.

another way have generic wrapper class this

[serializable] private class listwrapper<t> {     public list<t> items; } 

then create helper method

public static class jsonhelper {     public static list<t> tolist<t>(string json)     {         listwrapper<t> wrapper = jsonmapper.toobject<listwrapper<t>>(json);         return wrapper.items;     } } 

and use this

list<jsonicon> icons = jsonhelper.tolist<jsonicon>(jsonstring); 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -