2011-12-07 65 views
1

我目前正在研究一个大应用程序,并且发现了一些细节。可以将数组序列化并将其放入一个包中。然后把它放在一个意图,并开始活动。但在接收端,我必须通过痛苦的2步程序来反序列化数组。在Android上反序列化阵列

 MyObj[] data = (MyObj[])bundle.getSerializable("key"); // doesn't work 

    Object[] temp = (Object[])bundle.getSerializable("key"); 
    MyObj[] data2 = (MyObj[])temp, // doesn't work 

    MyObj[] data3 = new MyObj[temp.length]; // does work 
    for(int i = 0; i < temp.length; i++) { 
      data3[i] = (MyObj)temp[i]; 
    } 

那是我必须经历通过数组循环的原因是什么?

+0

这是不是一个Android特定的一个一般的Java问题一。谷歌搜索“Java铸造阵列”将为您的问题提供答案。 Java根本不允许向下投射阵列。 –

+0

相关http://stackoverflow.com/questions/1115230/casting-object-array-to-integer-array-error – Gray

回答

6

问题是,如果你有一个Object的数组,你投的是一个数组MyObj,编译器将不得不通过并验证数组中每个项目的类,以允许演员为MyObj[]。 Java语言设计者决定不这么做,并强迫程序员写出来。例如:

Object[] objs = new Object[] { "wow", 1L }; 
// this isn't allowed because the compiler would have to test each object itself 
String[] strings = (String[]) objs; 
// you wouldn't want an array access to throw the ClassCastException 
String foo = strings[1]; 

所以Java语言强制你自己做循环。

Object[] objs = new Object[] { "wow", 1L }; 
String[] strings = new String[objs.length]; 
for (int i = 0; i < objs.length; i++) { 
    // this can then throw a ClassCastException on this particular object 
    strings[i] = (String) objs[i]; 
} 

可以使用Arrays类(使用System.arraycopy()本地方法)来轻松地做到这一点:

MyObj[] data3 = Arrays.copyOf(temp, temp.length, MyObj[].class); 

参见:How to convert object array to string array in Java

0

您也可以使用JSON与它是非常非常容易序列化和反序列化一个数组,你不必在你的代码丑陋的强制转换:

Gson gson = new Gson(); 
int[] ints = {1, 2, 3, 4, 5}; 
String[] strings = {"abc", "def", "ghi"}; 

// Serialization 
gson.toJson(ints);  ==> prints [1,2,3,4,5] 
gson.toJson(strings); ==> prints ["abc", "def", "ghi"] 

// Deserialization 
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); 

来自实例:https://sites.google.com/site/gson/gson-user-guide#TOC-Array-Examples

+0

我使用Gson已经为服务器的json/rest通信,它比java de/serializing慢。所以我想我使用的是铸件。 – schlingel