-
-
Save vrudikov/7340e0c3c6e0c5489b3bcde54ec3a301 to your computer and use it in GitHub Desktop.
Basic Jackson Codec for Netty
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.fasterxml.jackson.databind.ObjectMapper; | |
import io.netty.buffer.ByteBuf; | |
import io.netty.buffer.ByteBufInputStream; | |
import io.netty.buffer.ByteBufOutputStream; | |
import io.netty.channel.ChannelHandlerContext; | |
import io.netty.handler.codec.ByteToMessageCodec; | |
import java.util.List; | |
public class BasicJacksonCodec<T> extends ByteToMessageCodec<T> { | |
private final Class<T> clazz; | |
private final ObjectMapper objectMapper; | |
public BasicJacksonCodec(Class<T> clazz, ObjectMapper objectMapper) { | |
super(clazz); | |
this.clazz = clazz; | |
this.objectMapper = objectMapper; | |
} | |
@Override | |
protected void encode(ChannelHandlerContext ctx, T msg, ByteBuf out) throws Exception { | |
ByteBufOutputStream byteBufOutputStream = new ByteBufOutputStream(out); | |
objectMapper.writeValue(byteBufOutputStream, msg); | |
} | |
@Override | |
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { | |
ByteBufInputStream byteBufInputStream = new ByteBufInputStream(in); | |
out.add(objectMapper.readValue(byteBufInputStream, clazz)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment