0

如何使用 Protostuff 像以下示例一样序列化对象:

 Map<String, Map<String, String>>

我知道我必须使用 MapSchema,但我不知道我需要对这个对象做什么。

4

1 回答 1

0

用于序列化外部 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 {

    }
}

序列化内部 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 {

    }
}
于 2017-08-01T11:12:45.947 回答