Avro序列化和反序列化List <uuid>

时间:2018-09-09 08:06:53

标签: encoding avro

我无法理解如何将List序列化为二进制格式并反序列化回List。我试图为此使用CustomEncoding:

public class ListUUIDAsListStringEncoding extends CustomEncoding<List<UUID>> {
    {
        schema = Schema.createArray(Schema.createUnion(Schema.create(Schema.Type.STRING)));
        schema.addProp("CustomEncoding", "com.my.lib.common.schemaregistry.encoding.ListUUIDAsListStringEncoding");
    }

    @Override
    protected void write(Object datum, Encoder out) throws IOException {
        var list = (List<UUID>) datum;
        out.writeArrayStart();
        out.setItemCount(list.size());
        for (Object r : list) {
            if (r instanceof UUID) {
                out.startItem();
                out.writeString(r.toString());
            }
        }
        out.writeArrayEnd();
    }

    @Override
    protected List<UUID> read(Object reuse, Decoder in) throws IOException {
        var newArray = new ArrayList<UUID>();

        for (long i = in.readArrayStart(); i != 0; i = in.arrayNext()) {
            for (int j = 0; j < i; j++) {
                newArray.add(UUID.fromString(in.readString()));
            }
        }

        return newArray;
    }

}

“写”方法似乎正确传递,但尝试读取字符串时,“读”方法因异常“ java.lang.ArrayIndexOutOfBoundsException:36”而停止。

我做错了什么以及如何正确反序列化数据?

1 个答案:

答案 0 :(得分:1)

解决了自己:

如果有人需要,请在此处放置我的编码类:

public class ListUuidAsNullableListStringEncoding extends CustomEncoding<List<UUID>> {
    {
        schema = Schema.createUnion(
            Schema.create(Schema.Type.NULL),
            Schema.createArray(Schema.create(Schema.Type.STRING))
        );
    }

    @Override
    protected void write(Object datum, Encoder out) throws IOException {
        if (datum == null) {
            out.writeIndex(0);
            out.writeNull();
        } else {
            out.writeIndex(1);
            out.writeArrayStart();
            out.setItemCount(((List) datum).size());
            for (Object item : (List) datum) {
                if (item instanceof UUID) {
                    out.startItem();
                    out.writeString(item.toString());
                }
            }
            out.writeArrayEnd();
        }
    }

    @Override
    protected List<UUID> read(Object reuse, Decoder in) throws IOException {
        switch (in.readIndex()) {
            case 1:
                var newArray = new ArrayList<UUID>();

                for (long i = in.readArrayStart(); i != 0; i = in.arrayNext()) {
                    for (int j = 0; j < i; j++) {
                        newArray.add(UUID.fromString(in.readString()));
                    }
                }

                return newArray;
            default:
                in.readNull();
                return null;
        }
    }

}