Gson - 使用嵌套的对象列表序列化对象列表 - 需要年龄

时间:2015-11-17 14:09:17

标签: java json serialization gson

在序列化每个对象包含其他对象列表的对象列表时,我遇到了严重的性能问题:

class Author {
    private String name;
    private List<Book> books;
}

class Book {
    private String name;
}

我有一个与此类似的结构。当我有一个包含8000个元素的List,并且每个Author实例有6本书时,这段代码大约需要40秒才能运行:

new Gson().toJson(authors);

我不认为这是正常的吗?我正在使用Gson 2.4版。

1 个答案:

答案 0 :(得分:3)

我准备了一个包含数据的例子

package gson;

import java.util.ArrayList;
import java.util.Random;

import com.google.gson.Gson;

public class GsonExample {

    private static final String[] arrNames = {"Jay","Willy","John","Gary","Franklin","Renee"};
    private static final String[] arrBooks = 
        {"The Hitchhiker's Guide to the Galaxy",
        "Pride and Prejudice and Zombies",
        "I Was Told There'd Be Cake",
        "The Hollow Chocolate Bunnies of the Apocalypse",
        "To Kill a Mockingbird",
        "The Unbearable Lightness of Being"};

    private static final int NUM_AUTHORS    = 8000;
    private static final int NUM_BOOKS      = 6;

    private static final boolean printResults   = true;

    public static void main(String[] args) {

        long startTime = System.currentTimeMillis();
        long estimatedTime = 0;

        ArrayList<Author> authors = new ArrayList<Author>();
        for (int i = 0; i < NUM_AUTHORS; i++) {
            authors.add(getDummyAuthor());
        }
        String json = new Gson().toJson(authors);

        if (printResults) {
            System.out.println(json);
        }

        estimatedTime = System.currentTimeMillis() - startTime;

        System.out.println("Estimated time: " + estimatedTime + " miliseconds");
    }

    private static Author getDummyAuthor() {
        Author author = new Author();
        ArrayList<Book> books = new ArrayList<Book>();
        Random rand = new Random();
        int randomValue = rand.nextInt(arrNames.length);
        String authorName = arrNames[randomValue];

        for (int i = 0; i < NUM_BOOKS; i++) {
            books.add(getDummyBook(i));
        }
        author.setName(authorName);
        author.setBooks(books);

        return author;
    }

    private static Book getDummyBook(int ixBook) {
        String bookName = arrBooks[ixBook];
        Book book = new Book(bookName);
        return book;
    }
}

平均时间约为10秒(打印数据)。没有打印时间约为300-400毫秒。您可能正在进行某种循环吗?