How to print the object json when JsonProperty is different of attribute?

Viewed 618

If I have any class, for example:


import com.fasterxml.jackson.annotation.JsonProperty;

class Person {

    @JsonProperty("alternativeName")
    private String name;
}

I have a instance of A with name = "test"

I would like to have in log:

Object Person(alternativeName=test, ... [other JsonProperty..])

How to get that object with the JsonProperty instead the attributes? Is there any way to get it?

1 Answers

The way it shows in your log depends on the toString() method. It usually includes the name of the attribute and does not handle @JsonProperty annotations. You have two ways of doing this:

  1. Change toString() implementation so that it prints alternativeName instead of name. The downside of this is that you will then need to adapt two Strings if you want to change alternativeName to anything else.
  2. Use ObjectMapper writeValueAsString() method in your log statement. This will take @JsonProperty into consideration but it will log Person as JSON and not as a regular POJO (as you depicted in your example).

Now you need to compromise and select what you consider being the best approach.

Related