1 回答

TA贡献1878条经验 获得超4个赞
我能想到的最灵活的方法是使用杰克逊的JsonAnyGetter注释。它允许您向 Jackson 提供Map您的 pojo 状态的表示。从 a 中过滤值Map可以以迭代方式完成。Map从包含s的 a 中过滤值Map可以递归方式完成。
这是我根据提供的问题构建的解决方案
public class Claim {
Map<String, Object> properties = new HashMap<>();
public Claim() {
// may be populated from instance variables
Map<String, String> person = new HashMap<>();
person.put("name", "Sam");
person.put("surname", "ngonma");
properties.put("person", person);
Map<String, String> car = new HashMap<>();
car.put("make", "Toyota");
car.put("model", "yaris");
properties.put("car", car);
}
// nullify map values based on provided array
public void filterProperties (String[] nullifyValues) {
filterProperties(properties, nullifyValues);
}
// nullify map values of provided map based on provided array
@SuppressWarnings("unchecked")
private void filterProperties (Map<String, Object> properties, String[] nullifyValues) {
// iterate all String-typed values
// if value found in array arg, nullify it
// (we iterate on keys so that we can put a new value)
properties.keySet().stream()
.filter(key -> properties.get(key) instanceof String)
.filter(key -> Arrays.asList(nullifyValues).contains(properties.get(key)))
.forEach(key -> properties.put(key, null));
// iterate all Map-typed values
// call this method on value
properties.values().stream()
.filter(value -> value instanceof Map)
.forEach(value -> filterProperties((Map<String, Object>)value, nullifyValues));
}
// provide jackson with Map of all properties
@JsonAnyGetter
public Map<String, Object> getProperties() {
return properties;
}
}
测试方法
public static void main(String[] args) {
try {
ObjectMapper mapper = new ObjectMapper();
Claim claim = new Claim();
claim.filterProperties(new String[]{"Sam", "Toyota"});
System.out.println(mapper.writeValueAsString(claim));
} catch (Exception e) {
e.printStackTrace();
}
}
输出
{"car":{"model":"yaris","make":null},"person":{"surname":"ngonma","name":null}}
添加回答
举报