Jackson JSON mapping of superclass value

22,027

Solution 1

I am not able to add annotations

You can add annotations using mix-ins. See http://wiki.fasterxml.com/JacksonMixInAnnotations for details.

Depending on what the rest of the class feild/method structures are, another approach that might work would be to configure visibility access of fields/methods through ObjectMapper. The following line demonstrates how to make such a configuration, not necessarily the specific configuration you need.

mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY));

I am using @JsonAutoDetect(JsonMethod.NONE) because I need only a small set of fields from the object, instead I am using @JsonProperty

I should have realized that was possible. I have to update my blog post. Thank you.

Solution 2

If you put the annotations on the getters (instead directly on the fields), you can override the getId() method (if it's not final in the superclass) and add an annotation to it.

class Parent {
  public long getId(){...};
  ...
}

@JsonAutoDetect(JsonMethod.NONE)
class Child extends Parent {

    private String title;

    @JsonProperty
    public String getTitle() {...}

    @Override
    @JsonProperty
    public long getId() {
        return super.getId();
    }
}
Share:
22,027
Ralph
Author by

Ralph

Updated on July 14, 2020

Comments

  • Ralph
    Ralph almost 4 years

    I am using Jackson 1.8.3 in a Spring application to map Java Objects to JSON.

    One of my Java Class (Child) extends an super class (Parent) that is part of an Libary, so I am not able to modify it. (Especially I am not able to add annotations.)

    I am using @JsonAutoDetect(JsonMethod.NONE) because I need only a small set of fields from the object, instead I am using @JsonProperty.

    class Parent {
      public long getId(){...};
      ...
    }
    
    @JsonAutoDetect(JsonMethod.NONE)
    class Child extends Parent {
    
        @JsonProperty
        private String title;
    }
    

    But one of the fields I need is an field id from the superclass, but I don't know how to tell Jackson to pay attention to this field, without modifying the parent class (because I can not modify it).

  • Ralph
    Ralph almost 13 years
    Thanks: I used the mixin approach
  • Ralph
    Ralph almost 13 years
    This is the most pragmatic way. But I used the approach mentioned by Programmer Bruce because it separates the different concerns.
  • Programmer Bruce
    Programmer Bruce almost 13 years
    Oh, yeah! Methods can be overridden.
  • happybuddha
    happybuddha over 7 years
    @Ralph - How ? I am in exact same situation.
  • Ralph
    Ralph over 7 years
    @happybuddha: read the linked article: in a very brief abstract: create the (abstract) Mixin class that contains only this line @JsonProperty("width") abstract long getId(); and then "assign" the mixin: objectMapper.getSerializationConfig().addMixInAnnotations(Ch‌​ild.class, MixIn.class);