简体   繁体   中英

Reading JSON data in netty server

This may be a "newb" question but here it goes anyway.
I am sending JSON data from netty client to netty server.
But the problem i am facing is netty server is not able to access/read JSON data.
In order to access JSON data in server, i need a encoder/decoder.
I am confused as to how to write this encoder/decoder ?
Anyone have any helpful ideas?

Use JSON-Simple or GSON for serialization

Then write back to the client with this :

String jsonPayload = ...;
ByteBuf buffer = Unpooled.copiedBuffer(jsonPayload, CharsetUtil.UTF_8));
ctx.write(buffer);

If it's an HTTP server don't forget to wrap your buffer in a DefaultHttpContent !

ctx.write(new DefaultHttpContent(buffer));

For inspiration look the following examples :

EDIT :

If you need to read the jsonPayload from your request, you could to this :

String jsonPayload = bytebuf.content().toString(CharsetUtil.UTF_8)

在这种情况下,我使用了JSON-Simple工具箱。

This is an old question However I think the answers here are not the best solutions. The code bellow is smarter about extra memory consumption

Parse:

public T parse(ByteBuf byteBuf) throws Exception {
    InputStream byteBufInputStream = new ByteBufInputStream(byteBuf);
    return objectMapper.readValue(byteBufInputStream, klass);
}

public ByteBuf byteBuf(T value) throws Exception {
    byte[] bytes = objectMapper.writeValueAsBytes(value);
    return Unpooled.wrappedBuffer(bytes);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM