Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing a field as json

I need to send a JSON body to REST service. Unfortunately, service is quite old and I need to send a POJO, containing JSON string field. So it looks like this:

class SomeData {
    int id;
    SomePojo jsonField;

    ...
}

So SomeData should be sent like this:

{'id': 1, 'jsonField': some_json_string}

I haven't found any Jackson magic annotation to make it works and I've got a doubt it can be made somehow because of type erasure in Java and it may not be possible to write custom serializer for this purpose but I'm not sure.

Could you please suggest any idea of how I can make it work or workaround the issue? Thank you very much in advance!

like image 834
Dmitry Senkovich Avatar asked Jun 18 '26 16:06

Dmitry Senkovich


1 Answers

You need to implement your own serialiser, you can then configure it at ObjectMapper level, e.g.:

ObjectMapper mapper = new ObjectMapper();

SimpleModule module = new SimpleModule();
module.addSerializer(SomeData.class, new SomeDataSerialiser());
mapper.registerModule(module);

You can find the complete example here.

like image 115
Darshan Mehta Avatar answered Jun 21 '26 04:06

Darshan Mehta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!