Abhishek
Abhishek

Reputation: 2019

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?

Upvotes: 2

Views: 10193

Answers (3)

Ilker Ike kucuk
Ilker Ike kucuk

Reputation: 101

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);
}

Upvotes: 0

Tony
Tony

Reputation: 1254

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)

Upvotes: 5

Dmitry Ginzburg
Dmitry Ginzburg

Reputation: 7461

In this case I used JSON-Simple toolkit.

Upvotes: 0

Related Questions