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?


Solution 1:

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 :

  • HttpHelloWorldServerHandler.java
  • HttpSnoopServerHandler

EDIT :

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

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