有一个遗留应用程序通过TCP执行json。
我使用netty服务器,我想通过Gson将json转换为Pojo。
为了做到这一点,我转换创建了一个Decoder,它将ByteBuf作为输入并创建My Object。
问题是Bytebuf的大小为1024,json比那个大得多(> 20mo)
@Sharable
public class RequestDecoder extends MessageToMessageDecoder<ByteBuf> {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
InputStream json = new ByteBufInputStream(msg);
InputStreamReader inputStreamReader = new InputStreamReader(json, Charsets.UTF_8);
JsonReader reader;
reader = new JsonReader(inputStreamReader);
reader.setLenient(true);
Request object = new Gson().fromJson(reader, Request.class);
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException("uncloseable reader", e);
}
out.add(object);
}
}
我总是得到:
com.google.gson.stream.MalformedJsonException: Unterminated string at line 1 column 1020
当我调试时,我只得到“ByteBuf msg”中的第一个1024字节
如何将ByteBuf容量设置为其最大容量? (调试时我看到ByteBuf是一个SimpleLeakAwareByteBuf,其maxCapacity为2147483647)
如何摆脱这种限制?
答案 0 :(得分:0)
尝试使用不同的解码器。例如,尝试ReplayingDecoder。
Netty中有许多解码器。您必须选择最合适的解码器并根据您的要求实施。
使用ReplayingDecoder时,请确保知道要准确读取的字节数。通常,要读取的字节大小在网络数据包的开头发送。这实际上取决于您的服务器+客户端协议实现。
答案 1 :(得分:0)
我在管道的开头添加了DelimiterBasedFrameDecoder:
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Unpooled.wrappedBuffer(new byte[]{'E', 'O', 'F', '\n'})));
因为我发现所有json都以“EOF \ n”终止(由于遗留问题)
现在对我来说没问题,但是当这个遗留问题得到解决后会发生什么?