有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:如何确保不打印某些JSON字段

我有一个需要发送到REST服务端点的文档请求:

@Data // lombok
public class Document {
    private String name;
    private String location; 
    private String content; // a base64 encoded byte array
}

我有一个实用程序类,可以用来在日志文件中记录整个JSON对象。因此,如果在运行时引发异常,代码将在错误级别记录导致异常的请求,如下所示:

{
     "name": "file1.pdf",
     "location" : "/root/folder/",
     "content" : "JVBERi0xLjQKJdP0zOEKJxxxxxxxxxxxxxxxxxxxx"
}

问题出在“内容”领域。如果文件非常大,“内容”字段将在运行时发生异常时很快填充日志文件。那么,如何使“内容”字段不打印在日志文件中呢?我考虑过使用@JsonIgnore,但是当请求被传递到端点时,它会使“content”字段被忽略吗?我没有使用Gson


共 (1) 个答案

  1. # 1 楼答案

    您可以使用JacksonMixin

    @Data
    public class Document {
        private String name;
        private String location; 
        private String content;
    }
    
    public static abstract class ContentIgnoreMixin {
        @JsonIgnore
        private String content;
    }
    
    // same as ContentIgnoreMixin, but interface using getter
    public interface class ContentIgnoreMixin2 {
        @JsonIgnore
        String getContent();
    }
    

    后来:

        ObjectMapper mapper = new ObjectMapper();
        mapper.addMixIn(Document.class, ContentIgnoreMixin.class);  // or ContentIgnoreMixin2 - no difference 
        String jsonWithoutContent = mapper.writeValueAsString(objectWithContent);