Home > Software engineering >  Jackson serialize object into String
Jackson serialize object into String

Time:07-19

I have the following class structure:

class A {
    B objB;
    int val;
    ...
}

class B {
    int val2;
}

Now, my current understanding is that JSON created for an object of class A with Jackson would look like this:

{
    "val":10,
    "objB":
    {
        "val2":20
    }
}

What I'm trying to achieve is a JSON that looks like this:

{
    "val":10,
    "objB":"MY_STRING"
}

This value of MY_STRING is computed based on the value of the integer val2. Is there a way I can achieve this in Jackson??

I see that I can create a custom serializer as suggested in https://www.baeldung.com/jackson-custom-serialization I can specify the custom serializer on Class A and write code that would serialize all the member variables in Class A, but that would require changing the serializer for A everytime I add/remove a member from Class A.

Is there a way that I can specify this custom serializer of class B and achieve the same result?

CodePudding user response:

@JsonValue could help:

class B {

  int val2;

  @JsonValue
  public String serialise() {
    return "foo:"   val2;
  }

}

CodePudding user response:

Also @JsonPropertyor even better @JsonGetter can do that. You can annotate some other methd instead of getVal2() as Json getter for that property. And that would do the trick. Read about it here: Jackson Annotation Examples

  • Related