使用GSON将Java复杂对象转换为JSON

时间:2014-03-24 12:51:09

标签: java android json gson

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

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 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。有更好的实施吗?可以修改类。

1 个答案:

答案 0 :(得分:0)

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

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