TL,DR 我应该在注释中使用哪些参数?跳转到第3部分。
我一直在努力争取"不那么好的文档" Jackson,即反序列化。正因为如此,我很抱歉很长的帖子,我有一些实现细节,我必须自己解决注释(并且有一个约束无法构建implementation TypeResolverBuilder)
注意: Jackson版本是2.X(FasterXML)。
直截了当地说,我有不同的JSON请求,我必须解释(第1部分)并将它们与数据模型匹配(第2部分)。我知道我可以使用@JsonTypeInfo和@JsonSubType注释,但我很难理解它,这就是为什么我要用一个完整的例子与你联系。
我想发布这三个不同的对象:
{ "animal" : {
"dog" : {
"name" : "Rex",
"owner" : "Mike",
"breed" : {
"lab" : {
"color" : "YELLOW",
"family" : {
"id" : null,
"shortName" : "GL of NE",
"longName" : "Great Labs of New England"
}
}
}
}}
{ "animal" : {
"dog" : {
"name" : "Rocky",
"owner" : "Bruce",
"breed" : {
"goldenRetriever" : {
"lifeSpan" : 15
}
}
}}
{ "animal" : {
"bird" : {
"color" : "BLUE"
}}
然后我们有这个模型我希望匹配JSON。
abstract class Animal {
private String _specie;
// usual getters and setters...
}
class Bird extends Animal {
private Color _color;
public Bird(Color color) {
super();
this._color = color;
}
// + usual getters and setters...
}
class Dog extends Animal {
private String _name;
private String _owner;
private Breed _breed;
public Dog(String dogName, String dogOwner, Breed dogBreed) {
super();
this._name = dogName;
this._owner = dogOwner;
this._breed = dogBreed;
}
// + usual getters and setters...
}
abstract class Breed {
private String _breedName;
// usual getters and setters...
}
class Lab extends Breed {
private Color _color;
private Family _family;
public Lab(Color color, Family family) {
super();
this._color = color;
this._family = family;
}
// + usual getters and setters...
}
class GoldenRetriever extends Breed {
private Integer _lifeSpan;
public GoldenRetriever(Integer lifeSpan) {
super();
this._lifeSpan = lifeSpan;
}
// + usual getters and setters...
}
class Family {
private String _id;
private String _longFamilyName;
private String _shortFamilyName;
// usual getters and setters...
}
enum Color {
BLUE("BLUE"),
YELLOW("YELLOW"):
private final _colorName:
public colorName() {
return this._colorName;
}
}
这里的主要问题是,
在@JsonTypeInfo上,我应该使用哪些参数来解释某些内容
{ ... {"dog": ... "breed" : { "lab" : { ... }}}}
(使用" lab"作为包装器?)。或者它应该在@JsonSubType上?
我应该如何声明Color类的注释,以便我只能将它与" color"匹配。 :" BLUE"?
我应该在何时何地使用@JsonCreator和@JsonProperty注释?
"使用","包括"和"财产"在@JsonTypeInfo上意味着什么?示例@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS,include = As.PROPERTY,property =" @ class")以及它们如何影响JSON反序列化?
谢谢!