我需要列出对象(某些MyBook)的(子)列表,并将其保存到android内部存储中。每个子列表都有一个名称。

我的书:

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 class ListOfMyBook extends ArrayList<MyBook>{
    public String listName;

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return listName;
    }

}


我当前的序列化和反序列化代码:

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的名称,也不会保存空的ListOfMyBook。有更好的实现吗?可以修改类。

最佳答案

因此,我实际上想出了自己的解决方案,即不扩展ArrayList<MyBook>而是创建一个像这样的新类:

public class ListOfMyBook implements Parcelable{
    public String listName;
    public List<MyBook> listOfBook = new ArrayList<MyBook>();
}

关于java - 使用GSON将Java复杂对象转换为JSON,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22609944/

10-09 23:26