基于Jackson的响应-在运行时修改属性而无需
MichałZiober 进行注释,在这里,我可以通过重写PropertyNamingStrategy来更改默认字段名称值:
这些是我收到的JSON示例(简体):
{"status": "OK","error": null,"data": { "difficulties": [{"value":"easy"},{"value":"medium"}]}}{"status": "ok", "error": null, "data": { "countries": [{"pre": "AT"},{"pre": "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的答案
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)