我正在创建一个Android应用程序,它将对象序列化并将它们存储到运行在cloud9 VM上的PostgreSQL数据库中。然后,当应用程序启动时,它将从数据库下载对象并对其进行反序列化。
我在尝试反序列化时遇到问题,因为它没有创建对象。我会提到我在Netbeans上测试了这个代码,如下所示。它可以工作。
//serialize - input is an arraylist of recipe objects
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(input);
String serialized_input = Base64.getEncoder().encodeToString(bos.toByteArray()); //bos.toString();
os.close();
//deserialize
ByteArrayInputStream bis = new ByteArrayInputStream(Base64.getDecoder().decode(serialized_input.getBytes()));
ObjectInputStream oInputStream = new ObjectInputStream(bis);
ArrayList<Recipe> input_Restored = (ArrayList<Recipe>)
oInputStream.readObject();
我的环境如下: PostgreSQL 9.3,服务器NodeJS / Express,postgresql适配器pg,cloud9 ubuntu VM,运行API 26的app工作室
这是我的SQL文件,我将序列化对象存储为文本。
drop database if exists recipes;
create database recipes;
\c recipes;
create table recipe (
idrecipe SERIAL,
userRecipes text NOT NULL,
adminRecipes text NOT NULL,
PRIMARY KEY (idrecipe)
);
这是我的快速api方法(可能不相关)
app.get('/add-recipe-admin', async (req, res) => {
var data = {obj: req.query.object};
console.log(data.obj+"\n");
await pool.query('update recipe set adminRecipes = $1', [data.obj]);
res.json({status: 'updated admin recipes'});
});
这是我在android studio中的序列化
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(RecipeList); //arraylist of objects
serialized_input = Base64.getEncoder().encodeToString(bos.toByteArray());
os.close();
LoginHandler lh = new LoginHandler();
jsonString = lh.makeServiceCall("https://cpsc-350-psethr.c9users.io:8082/add-recipe-admin?object="+serialized_input);
这是我在android studio中的反序列化
jsonString = lh.makeServiceCall("https://cpsc-350-psethr.c9users.io:8082/get-all-recipes");
JSONObject ob = new JSONObject(jsonString);
ByteArrayInputStream bis = new ByteArrayInputStream(Base64.getDecoder().decode(ob.get("adminrecipes").toString().getBytes()));
ObjectInputStream oInputStream = new ObjectInputStream(bis);
CreateRecipePage.RecipeList = (ArrayList<Recipe>) oInputStream.readObject(); //At this point it doesn't create any objects
我知道这可能不是将序列化对象存储在数据库中的最佳方法,但我正试图让它工作。我在这一点上不知所措,任何帮助都会非常感激。