joh*_*han 2 sqlite serialization android
我正在开发一个应用程序,我不断下载大量数据.
以json格式的数据和我使用Gson反序列化它.到现在为止,我将其存储在SQLite数据库中.我必须计算关系并将它们存储到关系数据库中.然而,这需要太多时间.
将类对象保存到db会更方便.
反序列化后数据看起来像这样:
Class A{
private String name;
private List<B> subItems;
}
Class B{
private String name;
private List<C> subItems
}
Run Code Online (Sandbox Code Playgroud)
我可以更容易地坚持这一点,例如通过使它们可序列化吗?如何才能做到这一点?
是的,序列化是一种更好的解决方案,适用于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;
}
Run Code Online (Sandbox Code Playgroud)
反序列化方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3578 次 |
| 最近记录: |