如何用gson反序列化json到bytebuffer?

rbl8hiat  于 2021-07-09  发布在  Java
关注(0)|答案(0)|浏览(596)

我正在尝试使用gson将来自kafka主题的对象反序列化为java对象。反序列化bytebuffer类型字段有问题。最初遇到的问题:

Error is: Class: class org.apache.kafka.common.errors.SerializationException:
Error deserializing key/value for partition PARTITION at offset 0. If needed, please seek past the record to continue consumption..
Cause: java.lang.RuntimeException: Unable to invoke no-args constructor for class java.nio.ByteBuffer. Registering an InstanceCreator with Gson for this type may fix this problem..
StackTrace: org.apache.kafka.common.errors.SerializationException: Error deserializing key/value for PARTITION at offset 0. If needed, please seek past the record to continue consumption.
Caused by: java.lang.RuntimeException: Unable to invoke no-args constructor for class java.nio.ByteBuffer. Registering an InstanceCreator with Gson for this type may fix this problem.

我尝试过这样注册自定义反序列化程序:

public class GsonByteBufferDeserializer implements JsonDeserializer<ByteBuffer> {

    @Override
    public ByteBuffer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        byte[] bytes = Base64.getDecoder().decode(json.getAsString());
        return ByteBuffer.wrap(bytes);
    }
}

还有一个错误:

Cause: java.lang.UnsupportedOperationException: JsonObject.
StackTrace: org.apache.kafka.common.errors.SerializationException: Error deserializing key/value for partition PARTITION at offset 0. If needed, please seek past the record to continue consumption.
Caused by: java.lang.UnsupportedOperationException: JsonObject
    at com.google.gson.JsonElement.getAsString(JsonElement.java:179)
    ....

现在我已经排除了bytebuffer字段,但这不是我的解决方案,因为我需要这些字段。
要反序列化的bytebuffer对象json表示示例:

{"hb":[72,-11,-71],"offset":0,"isReadOnly":false,"bigEndian":true,"nativeByteOrder":false,"mark":-1,"position":0,"limit":3,"capacity":3,"address":16}

有人知道让gson反序列化bytebuffer的工作方法吗?我无法将bytebuffer字段更改为任何其他类型。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题