1

I have this abstract class that provides some common properties to my entities. The following is an excerpt:

@MappedSuperclass
public class AbstractEntity implements Serializable {
    @Id
    @GeneratedValue
    private long id;

    @Temporal(value = TemporalType.TIMESTAMP)
    @JsonProperty(access = Access.READ_ONLY)
    private Date createdOn;

    @Temporal(value = TemporalType.TIMESTAMP)
    @JsonProperty(access = Access.READ_ONLY)
    private Date modifiedOn;

    ⋮
}

When serializing a subclass to JSON I get the expected results, for instance, this is an excerpt from serialization:

{
  "createdOn": "2016-12-11T15:35:23Z",
  "modifiedOn": "2016-12-11T15:35:23Z",
    ⋮
}

I need to have those common properties serialized to a JSON object such that the above example looks like this:

{
  "_metadata": {
    "createdOn": "2016-12-11T15:35:23Z",
    "modifiedOn": "2016-12-11T15:35:23Z",
  }
    ⋮
}

I have already tried using a class called Metadata and having a property of that type does works well. But I'm wondering if there's an easier or simpler way just using Jackson annotations?

  • It is possibly a duplicated question. See: [http://stackoverflow.com/questions/19158345/custom-json-deserialization-with-jackson](http://stackoverflow.com/questions/19158345/custom-json-deserialization-with-jackson) – Michael Gantman Dec 11 '16 at 18:34

1 Answers1

0

You can create an JPA @Embeddable class and you should get the desired output. Not sure what could be any simpler than that.

Embeddable:

@Embeddable
public class MetaData{

    @Temporal(value = TemporalType.TIMESTAMP)
    @JsonProperty(access = Access.READ_ONLY)
    private Date createdOn;

    @Temporal(value = TemporalType.TIMESTAMP)
    @JsonProperty(access = Access.READ_ONLY)
    private Date modifiedOn;
}

Entity:

@MappedSuperclass
public class AbstractEntity implements Serializable {
    @Id
    @GeneratedValue
    private long id;

    @Embedded
    private Metadata metdata;
}
Alan Hay
  • 22,665
  • 4
  • 56
  • 110
  • That is a solution that I tried and indeed it does work. The problem is that, by default, Spring Data REST does not includes the `id` in JSON serialization and I'd like to include it in the metadata object. I could pass it along a constructor but then I'm duplicating data, which is not elegant (among other things.) – Carlos A. Carnero Delgado Dec 12 '16 at 14:14