Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson JSON mapping of superclass value

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).

like image 797
Ralph Avatar asked Dec 16 '22 11:12

Ralph


1 Answers

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();
    }
}
like image 152
Nicolae Albu Avatar answered Jan 07 '23 05:01

Nicolae Albu