-4

I have a class that implements java.util.Set. For JSON serialization however, I want to represent instances of this class as a JSON object where elements of the set are represented by a custom String encoding, which is why the class has a synthetic property elements (i.e., there is no real attribute, the value is always computed on the fly).

public class MySet implements Set<...> {
   public String getElements() {
       // Return String encoding of the set's elements.
   }
   public void setElements(String encoding) {
       // Parse encoding and set elements of the set accordingly.
   }
   // A few more properties also accessible by getters/setters. 
}

The class has a few more properties, also accessible by getters/setters. They should also be JSON-serialized. All in all, all properties should be serialized as key/value pairs of a JSON object.

Intended JSON serialization:

{
   "elements": "...encoding...",
   // other properties as key/value pairs
}

In this regard, the class can be seen as a POJO. In fact, this is what I was assuming Jackson to consider; i.e., that Jackson would ignore the aspect that the class is also a Set. However, Jackson seems to prefer that the class is a Set and serializes it as such; i.e., an array JSON structure.

Is it possible to achieve this kind of de-/serializion just using @Json... annotations without the need to implement a custom de-/serializer?

twwwt
  • 438
  • 1
  • 4
  • 16
  • Why does your class implement `Set` although it is not a collection? This does not make any sense! – Seelenvirtuose Jul 22 '20 at 08:58
  • 10 secs search leads me here: https://stackoverflow.com/a/3956264/2185630 If I had 10 mins more... – dbl Jul 22 '20 at 08:59
  • @Seelenvirtuose: I have completely rewritten the question. Does it makes sense to you now? – twwwt Jul 30 '20 at 17:00
  • @dbl: I fail to see how the answer you are referring to is applicable here. In fact, I have seen it before I was creating this question here. Can you explain, please. – twwwt Jul 30 '20 at 17:03

1 Answers1

0

This can be achieved using the @JsonFormat annotation, essentially overriding Jackson's default behavior of serializing a Set:

@JsonFormat(shape = OBJECT)
public class MySet implements Set<...> {
   // ...
}

This has been tested successfully resulting in the intended JSON object structure described in the question.

twwwt
  • 438
  • 1
  • 4
  • 16