我有這些類:如何存儲對象和維護組成
class A implements Composite
{
Composite b = new B();
}
class B implements Composite
{
}
interface Composite
{
}
基本上A
由B
,我想它們存儲保持在這個文件組成。
在活動我這樣做:
String filename = "myfile.txt";
A a = new A();
Gson gson = new Gson();
String s = son.toJson(a);
FileOutputStream outputStream;
try
{
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(s.getBytes);
outputStream.close();
}
catch(Exception e)
{
}
然後我用這個代碼改爲:
FileInputStream fileInputStream = null;
try
{
fileInputStream = openFileInput(filename);
}
catch(FileNotFoundException e)
{}
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream)l;
BufferReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String line;
try
{
while((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line);
}
}
catch(IOException e)
{
}
String json = stringBuilder.toString();
Gson gson2 = new Gson();
// Exception here.
A a2 = gson2.fromJson(json, A.class);
問題是與對象B類裏面A. GSON似乎並不要知道B
的類型。所以,我得到這個異常:
JNI檢測應用程序錯誤:A,不是一個類中不能使 型複合
我更新並測試了我的答案,你也可以找到完整的代碼[這裏](https://gist.github.com/lelloman/a009a8b7c863071551c6dbc2d0fdaa0d) – lelloman