Protostuff serialize object like Map<String, Map<String, String>>

291 Views Asked by At

How can I serialize object like following example using Protostuff:

 Map<String, Map<String, String>>

I know that I must to use MapSchema, but I don't know what I need to do with this object.

1

There are 1 best solutions below

0
On

Class to serialize outer Map:

public class OuterMapSchema extends MapSchema<String, Map<String, String>> {

    InnerMapSchema INNER_MAP_SCHEMA = new InnerMapSchema();

    public OuterMapSchema() {
        super(MessageFactories.HashMap);
    }

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

    @Override
    protected void putValueFrom(Input input, MapWrapper<String, Map<String, String>> wrapper, String key) throws IOException {
        wrapper.put(key, input.mergeObject(null, INNER_MAP_SCHEMA));
    }

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

    @Override
    protected void writeValueTo(Output output, int fieldNumber, Map<String, String> value, boolean repeated) throws IOException {
        output.writeObject(fieldNumber, value, INNER_MAP_SCHEMA, repeated);

    }

    @Override
    protected void transferKey(Pipe pipe, Input input, Output output, int number, boolean repeated) throws IOException {

    }

    @Override
    protected void transferValue(Pipe pipe, Input input, Output output, int number, boolean repeated) throws IOException {

    }
}

Class to serialize inner Map:

public class InnerMapSchema extends MapSchema<String, String> {

    public InnerMapSchema() {
        super(MessageFactories.HashMap);
    }

    @Override
    protected String readKeyFrom(Input input, MapWrapper<String, String> wrapper) throws IOException {
        return input.readString();

    }

    @Override
    protected void putValueFrom(Input input, MapWrapper<String, String> wrapper, String key) throws IOException {
        wrapper.put(key, input.readString());
    }

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

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

    @Override
    protected void transferKey(Pipe pipe, Input input, Output output, int number, boolean repeated) throws IOException {

    }

    @Override
    protected void transferValue(Pipe pipe, Input input, Output output, int number, boolean repeated) throws IOException {

    }
}