Skip to content

Commit

Permalink
chore: Make DepthLimitingSerializer compute depth based on --selfRefe…
Browse files Browse the repository at this point in the history
…renceDepth
  • Loading branch information
en-milie committed Sep 27, 2024
1 parent 0235bf2 commit 0fb862b
Showing 1 changed file with 5 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,12 @@
* to exceed the maximum size that Jackson can serialize without streaming.
*/
public class DepthLimitingSerializer extends JsonSerializer<Object> {
private static final int MAX_DEPTH = 25;
private static int maxDepth;
private final ObjectMapper mapper = new ObjectMapper();
private final ThreadLocal<Integer> currentDepth = ThreadLocal.withInitial(() -> 0);

public DepthLimitingSerializer() {
public DepthLimitingSerializer(int depth) {
maxDepth = depth * 6;
this.mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}

Expand All @@ -37,7 +38,7 @@ public void serialize(Object value, JsonGenerator gen, SerializerProvider serial
private void serializeWithDepth(Object value, JsonGenerator gen) throws IOException {
int depth = currentDepth.get();

if (depth >= MAX_DEPTH || value == null) {
if (depth >= maxDepth || value == null) {
return;
}

Expand All @@ -58,7 +59,7 @@ private void serializeWithDepth(Object value, JsonGenerator gen) throws IOExcept
gen.writeStartObject();
for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
if (entry.getKey() != null && entry.getValue() != null) {
if (currentDepth.get() < MAX_DEPTH) {
if (currentDepth.get() < maxDepth) {
gen.writeFieldName(entry.getKey().toString());
serializeWithDepth(entry.getValue(), gen);
}
Expand Down

0 comments on commit 0fb862b

Please sign in to comment.