netty jsonobjectdecoder 简单示例
Netty提供了JsonObjectDecoder,用于从ByteBuf转换成为Json Object对象。下面是一个简单的示例代码:
```java
public class JsonDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
if (adableBytes() < 1) {
return;
}
int state = ST_INIT;
String fieldName = null;
Object value = null;
while (byteBuf.isReadable()) {
switch (state) {
case ST_INIT:
if (Byte() == '{') {
state = ST_DECODING_NORMAL;
} else {
state = ST_CORRUPTED;
}
break;
case ST_DECODING_NORMAL:
if (Byte() == '}') {
list.add(new JSONObject().put(fieldName, value));
decoder state = ST_INIT;
} else if (Byte() == '"') {
fieldName = readString(byteBuf);
state = ST_DECODING_FIELD_NAME;
} else if (Byte() == ':' && fieldName != null) {
value = readValue(byteBuf);
state = ST_DECODING_AFTER_COLON;
}
break;
case ST_DECODING_FIELD_NAME:
if (Byte() == '"') {
fieldName = readString(byteBuf);
state = ST_DECODING_AFTER_QUOTATION;
}
break;
case ST_DECODING_AFTER_QUOTATION:
if (Byte() == ',' || Byte() == '}') {
state = ST_DECODING_NORMAL;
}
break;
case ST_DECODING_AFTER_COLON:
if (Byte() == ',' || byteBuf
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论