1
我需要製作(子)對象列表(某些MyBook
)的列表並將其保存到android內部存儲器中。每個子列表都有一個名字。使用GSON將Java複雜對象轉換爲JSON
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(子表):
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);
}
這不救的ListOfMyBook
的名稱和它:
public class ListOfMyBook extends ArrayList<MyBook>{
public String listName;
@Override
public String toString() {
// TODO Auto-generated method stub
return listName;
}
}
我的序列化和反序列化當前的代碼不保存空的ListOfMyBook
。任何更好的實現?類可以修改。