2011-12-07 7 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

1。 "java casting arrays"のためのグーグルでは、あなたの問題に対する答えが得られます。 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]; 
} 

あなたは簡単にこれを行うには(System.arraycopy()ネイティブメソッドを使用しています)Arraysクラスを使用することができます。

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

参照:むしろアンドロイド特定のより一般的なJavaの質問です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

関連する問題