我做的和你在问题中所说的完全一样。
由于 Cloud Endpoints 对象已经序列化以通过线路传输,因此它们也可以序列化以存储在本地。作为额外的奖励,使用 Android 3.0 或更高版本,您甚至不需要导入任何库——它已经存在!例如:
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonFactory;
private static final JsonFactory JSON_FACTORY = new AndroidJsonFactory();
public void putObject(String key, Object value) throws Exception {
byte[] outputbytes = null;
if (value instanceof GenericJson) {
outputbytes = JSON_FACTORY.toByteArray(value);
} else {
ByteArrayOutputStream output = new ByteArrayOutputStream();
ObjectOutputStream objectstream = new ObjectOutputStream(output);
objectstream.writeObject(value);
objectstream.close();
outputbytes = output.toByteArray();
}
// persist "outputbytes" ...
}
public <T> T getObject(String key, Class<T> outclass) throws Exception {
// retrieve saved bytes...
byte[] valuebytes = ...
if (valuebytes[0] == '{' && valuebytes[1] == '"' && valuebytes[valuebytes.length-1] == '}') {
// Looks like JSON...
return JSON_FACTORY.fromString(new String(valuebytes, "UTF-8"), outclass);
} else {
ByteArrayInputStream input = new ByteArrayInputStream(valuebytes);
ObjectInputStream objectstream = new ObjectInputStream(input);
Object value = objectstream.readObject();
objectstream.close();
return outclass.cast(value);
}
}
请注意,AndroidJsonFactory
在序列化长字符串时,默认值(无论如何从 Android v4.3 开始)非常慢。JacksonFactory
如果您遇到性能问题,请创建一个新的。其他一切都保持不变。
更新: 如果你想序列化一个 GenericJson 对象列表,你只需要创建一个包含这些对象列表的 GenericJson 对象。例如:
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
public static class PersistantJson extends GenericJson {
@Key public int one;
@Key public String two;
}
public static class PersistantJsonList extends GenericJson {
@Key public List<PersistantJson> list = new ArrayList<PersistantJson>();
}
您现在可以将所有PersistantJson
(即“生成云端点客户端库”创建的某个类)对象添加到变量的.list
元素,PersistantJsonList
然后将该变量传递给putObject()
. 请注意,这要求列表中的所有对象都属于同一类,以便反序列化知道类型是什么(因为 JSON 序列化不记录类型)。如果您使用List<Object>
,那么回读的是 aList<Map<String, Object>>
并且您必须手动提取字段。