android - Java complex object to JSON with GSON -
i need make list of (sub)lists of objects (some mybook
) , save android internal storage. , each sublist has name.
mybook:
public class mybook implements parcelable{ string name; list<string> authors; string publisher; bitmap preview; string description; list<string> isbn; list<string> isbntype; //string isbn; string imglink=""; string googlelink =""; string publisheddate;
listofmybook (sublists):
public class listofmybook extends arraylist<mybook>{ public string listname; @override public string tostring() { // todo auto-generated method stub return listname; } }
my current code serialization , deserialization:
public static final string my_list_file = "mylist.json"; public static void exporttoxml(context context, list<listofmybook> listlistbook){ gson gson = new gson(); string json = gson.tojson(listlistbook); log.d("gson",json); fileoutputstream outputstream; try { outputstream = context.openfileoutput(my_list_file, context.mode_private); outputstream.write(json.getbytes()); outputstream.close(); } catch (exception e) { log.d("exporttoxml",e.tostring()); e.printstacktrace(); } } public static list<listofmybook> importfromxml(context context){ fileinputstream fis = null; try { fis = context.openfileinput(my_list_file); } catch (filenotfoundexception e) { // todo auto-generated catch block e.printstacktrace(); } inputstreamreader isr = new inputstreamreader(fis); bufferedreader bufferedreader = new bufferedreader(isr); stringbuilder sb = new stringbuilder(); string line; try { while ((line = bufferedreader.readline()) != null) { sb.append(line); } } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } string json = sb.tostring(); type listtype = new typetoken<list<listofmybook>>() {}.gettype(); gson gson = new gson(); return gson.fromjson(json, listtype); }
this not save name of listofmybook
, not save empty listofmybook
. better implementation? classes can modified.
so have came own solution not extend arraylist<mybook>
create new class this:
public class listofmybook implements parcelable{ public string listname; public list<mybook> listofbook = new arraylist<mybook>(); }
Comments
Post a Comment