简体   繁体   English

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

[英]Java complex object to JSON with GSON

I need to make a list of (sub)lists of objects (some MyBook ) and save it to android internal storage. 我需要列出对象(某些MyBook )的(子)列表并将其保存到android内部存储中。 And each sublist has a 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): ListOfMyBook(子列表):

public class ListOfMyBook extends ArrayList<MyBook>{
    public String listName;

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

}

My current code for serialization and 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 does not save the name of ListOfMyBook and it does not save empty ListOfMyBook . 这不会保存ListOfMyBook的名称,也不会保存空的ListOfMyBook Any better implementation? 还有更好的实现吗? Classes can be modified. 可以修改类。

So I have actually came up with my own solution which is to not extend ArrayList<MyBook> but create a new class like this: 因此,我实际上想出了自己的解决方案,即不扩展ArrayList<MyBook>而是创建一个像这样的新类:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM