2011-10-26 2 views
1

私はオブジェクトの配列を含むオブジェクトを持っています。私は、これらのオブジェクトにカスタムシリアライゼーションを使用するKryo(カスタムシリアライザ)でオブジェクトをシリアライズ

  • A)ストアを同じファイル

  • B)内のオブジェクトのこの配列をしたいと思います。

たとえば、私はTile [] []配列を持つMapオブジェクトを持っています。私は、オブジェクトを行う方法上のint型だけで罰金が、混乱して行うことができます。私はあなたがKryo V1を使用しているあなたの例から言うことができる

kryo.register(Map.class, new SimpleSerializer<Map>() { 
     public void write(ByteBuffer buffer, Map map) { 

      buffer.putInt(map.getId()); 
      System.out.println("Putting: " + map.getId()); 


     } 

     public Map read(ByteBuffer buffer) { 
      int id = buffer.getInt(); 
      System.out.println("Getting: " + id); 

      Map map = new Map(id, null, 0, 0, 0, 0); 

      return (map); 
     } 
    }); 

答えて

10

。私はKryo v2を使用することをお勧めします。

マップのシリアライザを設定しておき、各キーと値をシリアル化できます。各オブジェクトを直列化するには、Outputクラスを使用してデータを書き込み、Inputクラスを使用してデータを読み込むか、Kryoインスタンスのメソッドを呼び出してオブジェクトを処理させます。

組み込みのMapSerializerを使用する方が簡単です。 Tileオブジェクトのシリアライズをカスタマイズするだけで済みます。 KryoSerializableを拡張したり、シリアライザを登録したりすることができます。ここでは以下の例で...

public class Tile implements KryoSerializable { 
    int x, y; 
    Object something; 

    public void write (Kryo kryo, Output output) { 
     output.writeInt(x); 
     output.writeInt(y); 
     kryo.writeClassAndObject(output, something); 
    } 

    public void read (Kryo kryo, Input input) { 
     x = input.readInt(); 
     y = input.readInt(); 
     something = kryo.readClassAndObject(input); 
    } 
} 

ではなくKryoSerializableのシリアライザを使用して、別の例である:

public class Tile { 
    int x, y; 
    Object something; 
} 

kryo.register(Tile.class, new Serializer<Tile>() { 
    public void write (Kryo kryo, Output output, Tile object) { 
     output.writeInt(object.x); 
     output.writeInt(object.y); 
     kryo.writeClassAndObject(output, object); 
    } 

    public Tile read (Kryo kryo, Input input, Class<Tile> type) { 
     Tile tile = new Tile(); 
     kryo.reference(tile); // Only necessary if Kryo#setReferences is true AND Tile#something could reference this tile. 
     tile.x = input.readInt(); 
     tile.y = input.readInt(); 
     tile.something = kryo.readClassAndObject(input); 
     return tile; 
    } 
}); 

これはKryo#リファレンスへの呼び出しのreadメソッドではやや複雑ですKryoインスタンスを使用して子オブジェクトを逆シリアル化する前にこれは、参照をまったく使用しない場合、または「何か」のオブジェクトが、今作成したばかりのタイルを参照できないことが分かっている場合は省略できます。入力を使ってデータを読み込むだけの場合は、Kryo#参照を呼び出す必要はありません。

関連する問題