英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论