具有变量JsonProperty的Jackson泛型(与泛型一起使用)
我有一个看起来像这样的课:
public class Data<U> { @JsonProperty("difficulties")
private U[] data;
// ... geter setter constructor
}
而且我不想再创建10个类似的类,只是因为我只需要更改一行代码(在这种情况下为@JsonProperty(“
difficulties”))。该属性值取决于类型。可以在一堂课上写吗?
回答:
基于Jackson的响应-在运行时修改属性而无需
MichałZiober 进行注释,在这里,我可以通过重写PropertyNamingStrategy来更改默认字段名称值:
这些是我收到的JSON示例(简体):
{"status": "OK","error": null,"data": { "difficulties": [{"value":"easy"},{"value":"medium"}]
}}
{"status": "ok", "error": null, "data": {
"countries": [{"code": "AT"},{"code": "BE"}]
}}
请参阅第二行的区别,其中数据对象包含困难或国家(或基于上下文的许多其他名称)。
基于JSON响应的响应类:
public class Response<T>{ private String status;
private String error;
private Data<T> data;
// Getters Setters Constructors
}
基于JSON响应的数据类:
public class Data<T> { // property name, that will be changed
@JsonProperty(DataNamingStrategy.DATA_FIELD)
private T[] data;
// Getters Setters Constructors
}
这就是命名策略,它将默认值更改为运行时指定的值
public class DataNamingStrategy extends PropertyNamingStrategy{ // used by other classes (this will be default field name that should be changed)
public static final String DATA_FIELD = "variable:data";
private String fieldName;
public DataNamingStrategy(String fieldName) {
this.fieldName = fieldName;
}
// use this to change field name (format "variable":"value") not needed in my case
@Override
public String nameForField(MapperConfig<?> config, AnnotatedField field,
String defaultName) {
return (defaultName.equals(DATA_FIELD))?
fieldName :
super.nameForField(config, field, defaultName);
}
// use this to change setter method field name (JSON -> Object with format "variable":{})
@Override
public String nameForSetterMethod(MapperConfig<?> config,
AnnotatedMethod method, String defaultName) {
return (defaultName.equals(DATA_FIELD))?
fieldName :
super.nameForGetterMethod(config, method, defaultName);
}
// use this to change getter method field name (Object -> JSON with format "variable":{})
// should be same as nameForSetterMethod
@Override
public String nameForGetterMethod(MapperConfig<?> config,
AnnotatedMethod method, String defaultName) {
return nameForSetterMethod(config, method, defaultName);
}
}
用法应如下所示:
ObjectMapper mapper = new ObjectMapper();mapper.setPropertyNamingStrategy(new DataNamingStrategy(tableName));
JavaType type = mapper.getTypeFactory().constructParametricType(Response.class, dataClass);
Response<U> u = mapper.readValue(result, type);
其中result
是JSON作为字符串,tableName
是字符串,将在JSON,而不是缺省值使用,并且dataClass
是类U
(例如Difficulty.class)。
更好的用法PropertyNamingStrategy
应该是Map
代替String
。但是我只需要更改一个特定的值即可。
还可以查看PropertyNamingStrategy
文档,或者再次查看MichałZiober的答案
以上是 具有变量JsonProperty的Jackson泛型(与泛型一起使用) 的全部内容, 来源链接: utcz.com/qa/412282.html