从解析的JSON中排除/删除字段



我正在调用通过JSON并返回JSON的Web服务。我正在尝试为故障排除目的记录请求和响应。我想排除或杂交(通过 *(字段名称正则识别的任何密码值或其他任何密码值。我正在使用GSON进行JSON解析和序列化。我在我的logRequestlogResponse方法中包括以下toJson方法:

private String toJson(String str) {
    JsonElement elt = JSON_PARSER.parse(str);
    return GSON.toJson(elt);
}

我看不到任何对JsonParser对象上有帮助的东西。通过GsonBuilder构建Gson实例时,我尝试了各种方法。这种方法的困难似乎是我没有映射到Pojos,这将使我可以使用ExclusionStrategy。我目前的想法是递归检查JsonElement,我从parse方法中回来了,但是我不确定这是否有效,感觉很重,所以我想我会问。

以通用方式实施您的需求非常困难,因为通用JSON序列化的工作方式。有人已经在这里问了一个类似的问题:杰克逊:根据其属性将对象排除在序列化之外。在解析JSON字符串之后,看起来像是在JSON对象上遍历JSON对象,识别密码字段并明确对值进行清理,然后再将其序列序列返回到记录器中,如果您更喜欢遵循此路径,则可能是一个不错的选择。

但是,只要您知道要登录的文档的JSON模式,就可以更容易解决该问题。在这种情况下,您可以使用 jsonschema2pojo-maven-plugin 从架构中生成Java Pojo对象,然后将Gson库与序列化排除策略一起使用。这是一个示例:

    String jsonString = "{"name":"parent","id":"parentId","password":"topsecret"" +
            ","childPojo":{"name":"child","id":"childId","password":"topsecret"}}";
    RegexFieldExclusionStrategy strategy = new RegexFieldExclusionStrategy("pass.*");
    Gson gson = new GsonBuilder()
            .addSerializationExclusionStrategy(strategy)
            .create();
    MyPojo myPojo = gson.fromJson(jsonString, MyPojo.class);
    String json = gson.toJson(myPojo);
    System.out.println(json);

mypojo 类:

public class MyPojo {
  private String name;
  private String id;
  private String password;
  private MyPojo childPojo;
  public String getName() {
      return name;
  }
  public void setName(String name) {
      this.name = name;
  }
  public String getId() {
      return id;
  }
  public void setId(String id) {
      this.id = id;
  }
  public String getPassword() {
      return password;
  }
  public void setPassword(String password) {
      this.password = password;
  }
  public MyPojo getChildPojo() {
      return childPojo;
  }
  public void setChildPojo(MyPojo childPojo) {
      this.childPojo = childPojo;
  }
}

请注意,此Pojo是手动实现,可以使用上述插件来替换生成的插件,以简化整个过程。

Regexfieldexclusionstrategy 类:

import java.util.regex.Pattern;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
public class RegexFieldExclusionStrategy implements ExclusionStrategy {
  private String regex;
  public RegexFieldExclusionStrategy(String regex) {
      Pattern.compile(regex);
      this.regex = regex;
  }
  public boolean shouldSkipClass(Class<?> f) {
      return false;
  }
  public boolean shouldSkipField(FieldAttributes f) {
      return f.getName().toLowerCase().matches(regex);
  }
}

该程序将输出以下JSON文档:

{"name":"parent","id":"parentId","childPojo":{"name":"child","id":"childId"}}

最新更新