我正在开发一个应用程序,我不断下载大量数据。
以json格式的数据,我使用Gson对其进行反序列化。到现在为止,我将其存储在SQLite数据库中。我必须计算关系并将它们存储到关系数据库中。然而,这需要太多时间。
将类对象保存到db会更方便。
反序列化后数据看起来像这样:
Class A{
private String name;
private List<B> subItems;
}
Class B{
private String name;
private List<C> subItems
}
我能否以更简单的方式坚持这一点,例如将它们序列化?如何才能做到这一点?
答案 0 :(得分:7)
是的,序列化是一种更好的解决方案,适用于Android,适用于Android。以下示例取自http://www.jondev.net/articles/Android_Serialization_Example_%28Java%29
序列化方法:
public static byte[] serializeObject(Object o) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(o);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
return buf;
} catch(IOException ioe) {
Log.e("serializeObject", "error", ioe);
return null;
}
反序列化方法:
public static Object deserializeObject(byte[] b) {
try {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b));
Object object = in.readObject();
in.close();
return object;
} catch(ClassNotFoundException cnfe) {
Log.e("deserializeObject", "class not found error", cnfe);
return null;
} catch(IOException ioe) {
Log.e("deserializeObject", "io error", ioe);
return null;
}