Skip to content

Field beneath an array that is sometimes null cannot have a type other than varies #398

Closed
@ghost

Description

In a response containing an array, certain fields could be sometimes null and sometimes not. Currently JsonFieldTypeResolver marks them as Varies. This forces me to document the fields as Varies. Which IMO doesnt add any value to the docs. This leads to following error.

org.springframework.restdocs.payload.FieldTypesDoNotMatchException: The documented type of the field '[].obj' is Array but the actual type is Varies

Would it wise to make an exception for null?

here is an example patch

diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonFieldTypeResolver.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonFieldTypeResolver.java
index 25c373c..e618a4b 100644
--- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonFieldTypeResolver.java
+++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/payload/JsonFieldTypeResolver.java
@@ -35,10 +35,10 @@ class JsonFieldTypeResolver {
                        JsonFieldType commonType = null;
                        for (Object item : (Collection<?>) field) {
                                JsonFieldType fieldType = determineFieldType(item);
-                               if (commonType == null) {
+                               if (commonType == null && fieldType !== JsonFieldType.NULL) {
                                        commonType = fieldType;
                                }
-                               else if (fieldType != commonType) {
+                               else if (fieldType != commonType && fieldType !== JsonFieldType.NULL) {
                                        return JsonFieldType.VARIES;
                                }
                        }

I could use @JsonInclude(JsonInclude.Include.NON_NULL) to prevent null fields in REST response but I'd like to avoid that and use null and have consistent REST response with all fields.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions