java - 带变量JsonProperty的Jackson泛型( 使用泛型的用法)

  显示原文与译文双语对照的内容

我有一个类似这样的类:


public class Data<U> {

 @JsonProperty("difficulties")
 private U[] data;

//... geter setter constructor
}

我不想创建 10个类似的类,只是因为我需要改变一行代码( @JsonProperty ("在这种情况下的") 。 属性值取决于类型。 有可能把它写在一个班级里?

时间:

以下是我收到的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的JSON,tableName 是字符串,而不是默认值,dataClassU ( 例如 difficulty.class )的类。

更好的PropertyNamingStrategy 使用应该是 Map 而不是一个 String 。 但我只需要改变一个特定的价值。

...