将类似于POJO的Java Set对象序列化

huangapple go评论40阅读模式
英文:

Serialize Java Set-like object like a POJO

问题

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

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?

答案1

得分: 0

这可以通过使用@JsonFormat注解来实现,从本质上覆盖了Jackson默认序列化Set的行为:

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

已经成功测试过,生成了问题描述中所期望的JSON对象结构。

英文:

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.

huangapple
  • 本文由 发表于 2020年7月22日 16:55:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63030485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定