2015-10-07 2 views
1

- это любой метод сериализации java.util.Map для байтового массива при использовании protostuff, Я видел, что в файле protostuff-collectionsschema.jar есть MapSchema, но не знаю как это использовать. может кто-нибудь дать мне пример кода, заранее.как сериализовать карту в байтовый массив protostuff

ответ

0

Если вам необходимо сериализовать и десериализовать Map, то вы должны обернуть его как поле в класс-оболочку (для создания схемы).

После этого вы можете сериализовать/десериализовать данные в двоичном формате (или json, если хотите текст, читаемый человеком) с помощью RuntimeSchema.

public class Foo { 
    private Map<Integer, String> map; 

сериализации и десериализации код может выглядеть следующим образом:

private final LinkedBuffer BUFFER = LinkedBuffer.allocate(); 
private final Schema<Foo> SCHEMA = RuntimeSchema.getSchema(Foo.class); 

@Test 
public void serializeAndDeserialize() throws Exception { 
    Foo foo = createFooInstance(); 
    byte[] bytes = serialize(foo); 
    Foo x = deserialize(bytes); 
    Assert.assertEquals(foo, x); 
} 

private byte[] serialize(Foo foo) throws java.io.IOException { 
    return ProtobufIOUtil.toByteArray(foo, SCHEMA, BUFFER); 
} 

private Foo deserialize(byte[] bytes) { 
    Foo tmp = SCHEMA.newMessage(); 
    ProtobufIOUtil.mergeFrom(bytes, tmp, SCHEMA); 
    return tmp; 
} 

исходный код Полный для этого примера: RuntimeSchemaUsage.java

0

Вы можете быть в protostuff - collectionschema найдено в тестовом коде.

public class StringMapSchema<V> extends MapSchema<String,V> 
{ 

    /** 
    * The schema for Map<String,String> 
    */ 
    public static final StringMapSchema<String> VALUE_STRING = new StringMapSchema<String>(null) 
    { 
     protected void putValueFrom(Input input, MapWrapper<String,String> wrapper, 
       String key) throws IOException 
     { 
      wrapper.put(key, input.readString()); 
     } 

     protected void writeValueTo(Output output, int fieldNumber, String value, 
       boolean repeated) throws IOException 
     { 
      output.writeString(fieldNumber, value, repeated); 
     } 

     protected void transferValue(Pipe pipe, Input input, Output output, int number, 
       boolean repeated) throws IOException 
     { 
      input.transferByteRangeTo(output, true, number, repeated); 
     } 
    }; 

    /** 
    * The schema of the message value. 
    */ 
    public final Schema<V> vSchema; 
    /** 
    * The pipe schema of the message value. 
    */ 
    public final Pipe.Schema<V> vPipeSchema; 

    public StringMapSchema(Schema<V> vSchema) 
    { 
     this(vSchema, null); 
    } 

    public StringMapSchema(Schema<V> vSchema, Pipe.Schema<V> vPipeSchema) 
    { 
     this.vSchema = vSchema; 
     this.vPipeSchema = vPipeSchema; 
    } 

    protected final String readKeyFrom(Input input, MapWrapper<String,V> wrapper) 
    throws IOException 
    { 
     return input.readString(); 
    } 

    protected void putValueFrom(Input input, MapWrapper<String,V> wrapper, String key) 
    throws IOException 
    { 
     wrapper.put(key, input.mergeObject(null, vSchema)); 
    } 

    protected final void writeKeyTo(Output output, int fieldNumber, String value, 
      boolean repeated) throws IOException 
    { 
     output.writeString(fieldNumber, value, repeated); 
    } 

    protected void writeValueTo(Output output, int fieldNumber, V value, 
      boolean repeated) throws IOException 
    { 
     output.writeObject(fieldNumber, value, vSchema, repeated); 
    } 

    protected void transferKey(Pipe pipe, Input input, Output output, int number, 
      boolean repeated) throws IOException 
    { 
     input.transferByteRangeTo(output, true, number, repeated); 
    } 

    protected void transferValue(Pipe pipe, Input input, Output output, int number, 
      boolean repeated) throws IOException 
    { 
     if(vPipeSchema == null) 
     { 
      throw new RuntimeException("No pipe schema for value: " + 
        vSchema.typeClass().getName()); 
     } 

     output.writeObject(number, pipe, vPipeSchema, repeated); 
    } 

} 
Смежные вопросы