Two standard features that could help:
1. If class implement `JsonSerializable`, its
public void serialize(JsonGenerator gen, SerializerProvider
serializers) throws IOException;
will be called to allow you to properly serialize it using generator
that is property configured
2 If a method of the class is annotation with `@JsonValue`, its return
value is serialized instead of instance itself:
often return value is something generic like `Map` or `ObjectNode`,
but could be some other POJO too, in case
transformations or clean up is needed
-+ Tatu +-
On Sun, Apr 15, 2018 at 9:16 AM, <[email protected]> wrote:
> I know I can use (new ObjectMapper()).convertValue(this, ObjectNode.class)
> to serialise given object to JSON. Is there a way to tell the lib to use a
> method inside that class to serialise it ?
>
>
> My classes:
>
>
> interface A {
> ObjectNode toJSON();
> }
>
> abstract class Tokens {
> Map<String, String> tokends;
> }
>
> class Foo extends Tokens implements A {
> private long id;
> private Bar bar;
>
> // Constructors, getters & setters...
>
> @Override
> public ObjectNode toJSON() {
> ObjectNode node = (new ObjectMapper()).convertValue(this,
> ObjectNode.class);
> tokens.forEach(node::put);
>
> return node;
> }
> }
>
> class Bar extends Tokens implements A {
> private long id;
>
> // Constructors, getters & setters...
>
> @Override
> public ObjectNode toJSON() {
> ObjectNode node = (new ObjectMapper()).convertValue(this,
> ObjectNode.class);
> tokens.forEach(node::put);
>
> return node;
> }
> }
>
>
>
> Now if I call (new A()).toJSON() I will get:
>
>
> {
> "id": 1,
> "bar": {
> "id": 2
> },
> "token1": "...",
> "token2": "...:,
> }
>
>
> Instead of:
>
> {
> "id": 1,
> "bar": {
> "id": 2,
> "token3": "...",
> "token4": "..."
> },
> "token1": "...",
> "token2": "...:,
> }
>
>
> I understand that this happens because the first method modifies the
> serialised class but is not called by jackson when it goes into child
> objects.
>
> Is there a way to tell jaskson to use toJSON method to create the child with
> tokens as well ?
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "jackson-user" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> To post to this group, send email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
--
You received this message because you are subscribed to the Google Groups
"jackson-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
For more options, visit https://groups.google.com/d/optout.