Skip to content

JsonDeserializer raises NPE if targetType is an array #869

@oranje42

Description

@oranje42

Spring-Kafka version: 2.2.0

The following code snippet produces an NPE (the error occurs with any array type, String[] is just used as an example here):

JsonDeserializer<String[]> deserializer = new JsonDeserializer<>(String[].class);

The stacktrace is as follows:

Exception in thread "main" java.lang.NullPointerException
	at org.springframework.kafka.support.serializer.JsonDeserializer.addTargetPackageToTrusted(JsonDeserializer.java:299)
	at org.springframework.kafka.support.serializer.JsonDeserializer.<init>(JsonDeserializer.java:180)
	at org.springframework.kafka.support.serializer.JsonDeserializer.<init>(JsonDeserializer.java:142)
	at org.springframework.kafka.support.serializer.JsonDeserializer.<init>(JsonDeserializer.java:130)

The error is caused in method addTargetPackageToTrusted because this.targetType.getPackage() returns null for array types:

private void addTargetPackageToTrusted() {
    if (this.targetType != null) {
        addTrustedPackages(this.targetType.getPackage().getName());
    }
}

A possible fix could be as follows (this one would also work for arrays of primitive types, like int[]):

private void addTargetPackageToTrusted() {
    if (this.targetType != null) {
        Package targetPackage = resolvePackage(this.targetType);
        if (targetPackage != null) {
            addTrustedPackages(targetPackage.getName());
        }
    }
}

// this method might still return null if the provided type represents a primitive array type, as int[]
private Package resolvePackage(Class<?> type) {
    return (type.isArray() ? type.getComponentType() : type).getPackage();
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions