Skip to content

@SpringQueryMap nested object support #442

Closed

Description

@zxy-c

FeignClient

interface MyFeignClient{
    @GetMapping(params = {"projection=wishSummary"})
   Object get(
            @SpringQueryMap MyObject myObject);
}

MyObject

class MyObject{
   Range range;
}
class Range{
  Integer from;
  Integer to;
}

Feign will build query param like "Range(from=1,to=2)" when I call MyFeignClient.get

I need a query param like "range.from=1&range.to=2" at the example

Activity

  1. added
    enhancement
    help wanted
    and removed on Jan 20, 2021
  2. o2-mesmer commented on Feb 11, 2021

    @o2-mesmer

    @zxy-c You can define a custom feign.QueryMapEncoder and wire it through the FeignClient's configuration.

  3. duzhongyuan commented on Oct 9, 2021

    @duzhongyuan

    For nested object, Collection nested objects. Rewrite FieldQueryMapEncoder .java

    public class CustomNestedObjectQueryMapEncoder implements QueryMapEncoder {
    
        private final Map<Class<?>, CustomNestedObjectQueryMapEncoder.ObjectParamMetadata> classToMetadata =
                new HashMap<Class<?>, CustomNestedObjectQueryMapEncoder.ObjectParamMetadata>();
    
        @Override
        public Map<String, Object> encode(Object object) throws EncodeException {
            return encodeInternal(null, object, null);
        }
    
        private Map<String, Object> encodeInternal(String prefixName, Object object, Map<String, Object> fieldNameToValue) {
            if (null == fieldNameToValue) {
                fieldNameToValue = Maps.newHashMap();
            }
    
            try {
                CustomNestedObjectQueryMapEncoder.ObjectParamMetadata metadata = getMetadata(object.getClass());
                for (Field field : metadata.objectFields) {
                    Object value = field.get(object);
    
                    if (value != null && value != object) {
                        Param alias = field.getAnnotation(Param.class);
                        String name = alias != null ? alias.value() : field.getName();
    
                        if (StringUtils.isNotBlank(prefixName)) {
                            name = prefixName + "." + name;
                        }
    
                        ClassLoader classLoader = value.getClass().getClassLoader();
    
                        if (classLoader == null) {
    
                            processNameAndValue(name, value, fieldNameToValue);
    
                        } else {
                            // Recursive call
                            encodeInternal(name, value, fieldNameToValue);
                        }
                    }
                }
    
                return fieldNameToValue;
            } catch (IllegalAccessException e) {
                throw new EncodeException("Failure encoding object into query map", e);
            }
        }
    
        private void processNameAndValue(String name, Object value, Map<String, Object> fieldNameToValue) throws IllegalAccessException {
            // Determines whether it is a custom object collection
            if (isCustomObjectCollection(value)) {
                Collection collection = (Collection) value;
    
                for (int i = 0; i < collection.size(); i++) {
                    Object element = ((ArrayList) collection).get(i);
    
                    ObjectParamMetadata metadata = getMetadata(element.getClass());
    
                    for (Field field : metadata.objectFields) {
                        Object elementValue = field.get(element);
    
                        if (elementValue != null && elementValue != element) {
                            Param alias1 = field.getAnnotation(Param.class);
                            String elementName = alias1 != null ? alias1.value() : field.getName();
    
                            elementName = name + "[" + i + "]." + elementName;
    
                            ClassLoader classLoader1 = elementValue.getClass().getClassLoader();
    
                            if (classLoader1 == null) {
    
                                if (isCustomObjectCollection(elementValue)) {
                                    // Recursive call
                                    processNameAndValue(elementName, elementValue, fieldNameToValue);
                                } else {
                                    fieldNameToValue.put(elementName, elementValue);
                                }
                            }
    
                        }
                    }
                }
            } else {
                fieldNameToValue.put(name, value);
            }
        }
    
        private boolean isCustomObjectCollection(Object value) {
            return value instanceof Collection
                    && !((Collection) value).isEmpty()
                    && ((Collection) value).iterator().next().getClass().getClassLoader() != null;
        }
    
        private CustomNestedObjectQueryMapEncoder.ObjectParamMetadata getMetadata(Class<?> objectType) {
            CustomNestedObjectQueryMapEncoder.ObjectParamMetadata metadata = classToMetadata.get(objectType);
            if (metadata == null) {
                metadata = CustomNestedObjectQueryMapEncoder.ObjectParamMetadata.parseObjectType(objectType);
                classToMetadata.put(objectType, metadata);
            }
            return metadata;
        }
    
        private static class ObjectParamMetadata {
    
            private final List<Field> objectFields;
    
            private ObjectParamMetadata(List<Field> objectFields) {
                this.objectFields = Collections.unmodifiableList(objectFields);
            }
    
            private static CustomNestedObjectQueryMapEncoder.ObjectParamMetadata parseObjectType(Class<?> type) {
                List<Field> allFields = new ArrayList();
    
                for (Class currentClass = type; currentClass != null; currentClass =
                        currentClass.getSuperclass()) {
                    Collections.addAll(allFields, currentClass.getDeclaredFields());
                }
    
                return new CustomNestedObjectQueryMapEncoder.ObjectParamMetadata(allFields.stream()
                        .filter(field -> !field.isSynthetic())
                        .peek(field -> field.setAccessible(true))
                        .collect(Collectors.toList()));
            }
        }
    
    }
    `
    
    ### NestedObjectFeignConfig 
    `public class NestedObjectFeignConfig {
    
        @Bean
        @Scope("prototype")
        @ConditionalOnProperty(name = "feign.hystrix.enabled")
        public Feign.Builder feignHystrixBuilder() {
            HystrixFeign.Builder encoder = HystrixFeign.builder();
            encoder.queryMapEncoder(new CustomNestedObjectQueryMapEncoder());
    
            return encoder;
        }
    
    }
    
    public interface TestClient {
    
    
        @GetMapping("/test-center/tapTest/getTapRecordReqDTO")
        CommonResponse<QueryJourneyResponseDTO> queryJourney(@SpringQueryMap HelloDTO HelloDTO);
    }
    
    public class HelloDTO {
        private String name;
    
        private WorldDTO worldDTO;
    
        private List<String> list;
    
        private List<WorldDTO> worldDTOList;
    }`
    
    public class WorldDTO {
        private String world;
    
        private String live;
    
        private List<TestDTO> testDTOList;
    }
    
    public class TestDTO {
    
        private String testName;
    
    }
    
  4. OlgaMaciaszek commented on Feb 14, 2022

    @OlgaMaciaszek
    Collaborator

    @duzhongyuan Would you like to provide a PR?

  5. yulgutlin commented on May 31, 2022

    @yulgutlin

    Needed this in my project with spring data pageable support and i slightly changed @duzhongyuan 's and @OlgaMaciaszek 's solution: fixed other collection types support, fixed enums and enum collections support. In case if someone will need that:

    import feign.Param;
    import feign.codec.EncodeException;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.cloud.openfeign.support.PageableSpringQueryMapEncoder;
    
    import java.lang.reflect.Field;
    import java.util.*;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    import static java.util.function.Predicate.not;
    
    /**
     * CustomNestedObjectQueryMapEncoder
     */
    public class CustomNestedObjectQueryMapEncoder extends PageableSpringQueryMapEncoder {
    
        private final Map<Class<?>, CustomNestedObjectQueryMapEncoder.ObjectParamMetadata> classToMetadata = new HashMap<>();
    
        @Override
        public Map<String, Object> encode(Object object) throws EncodeException {
            if (super.supports(object)) {
                return super.encode(object);
            }
            return encodeInternal(null, object, null);
        }
    
        private Map<String, Object> encodeInternal(String prefixName, Object object, Map<String, Object> fieldNameToValue) {
            if (null == fieldNameToValue) {
                fieldNameToValue = new HashMap<>();
            }
    
            try {
                CustomNestedObjectQueryMapEncoder.ObjectParamMetadata metadata = getMetadata(object.getClass());
                for (Field field : metadata.objectFields) {
                    Object value = field.get(object);
    
                    if (value != null && value != object) {
                        Param alias = field.getAnnotation(Param.class);
                        String name = alias != null ? alias.value() : field.getName();
    
                        if (StringUtils.isNotBlank(prefixName)) {
                            name = prefixName + "." + name;
                        }
    
                        Class<?> aClass = value.getClass();
                        ClassLoader classLoader = aClass.getClassLoader();
    
                        if (classLoader == null || aClass.isEnum()) {
    
                            processNameAndValue(name, value, fieldNameToValue);
    
                        } else {
                            // Recursive call
                            encodeInternal(name, value, fieldNameToValue);
                        }
                    }
                }
                return fieldNameToValue;
            } catch (IllegalAccessException e) {
                throw new EncodeException("Failure encoding object into query map", e);
            }
        }
    
        private void processNameAndValue(String name, Object value, Map<String, Object> fieldNameToValue) throws IllegalAccessException {
            // Determines whether it is a custom object collection
            if (isCustomObjectCollection(value)) {
                Collection<?> collection = (Collection<?>) value;
    
                int i = 0;
                for (Object element : collection) {
                    ObjectParamMetadata metadata = getMetadata(element.getClass());
    
                    for (Field field : metadata.objectFields) {
                        Object elementValue = field.get(element);
    
                        if (elementValue != null && elementValue != element) {
                            Param alias1 = field.getAnnotation(Param.class);
                            String elementName = alias1 != null ? alias1.value() : field.getName();
    
                            elementName = name + "[" + i + "]." + elementName;
    
                            ClassLoader classLoader1 = elementValue.getClass().getClassLoader();
    
                            if (classLoader1 == null) {
    
                                if (isCustomObjectCollection(elementValue)) {
                                    // Recursive call
                                    processNameAndValue(elementName, elementValue, fieldNameToValue);
                                } else {
                                    fieldNameToValue.put(elementName, elementValue);
                                }
                            }
                        }
                    }
                    i++;
                }
            } else {
                fieldNameToValue.put(name, value);
            }
        }
    
        private boolean isCustomObjectCollection(Object value) {
            return Optional.ofNullable(value)
                    .filter(Collection.class::isInstance)
                    .map(Collection.class::cast)
                    .filter(not(Collection::isEmpty))
                    .stream()
                    .flatMap(collection -> (Stream<?>) collection.stream())
                    .filter(not(Enum.class::isInstance))
                    .map(Object::getClass)
                    .map(Class::getClassLoader)
                    .anyMatch(Objects::nonNull);
        }
    
        private CustomNestedObjectQueryMapEncoder.ObjectParamMetadata getMetadata(Class<?> objectType) {
            CustomNestedObjectQueryMapEncoder.ObjectParamMetadata metadata = classToMetadata.get(objectType);
            if (metadata == null) {
                metadata = CustomNestedObjectQueryMapEncoder.ObjectParamMetadata.parseObjectType(objectType);
                classToMetadata.put(objectType, metadata);
            }
            return metadata;
        }
    
        private static class ObjectParamMetadata {
            private final List<Field> objectFields;
    
            private ObjectParamMetadata(List<Field> objectFields) {
                this.objectFields = Collections.unmodifiableList(objectFields);
            }
    
            private static CustomNestedObjectQueryMapEncoder.ObjectParamMetadata parseObjectType(Class<?> type) {
                List<Field> allFields = new ArrayList<>();
    
                for (Class<?> currentClass = type; currentClass != null && !currentClass.isEnum(); currentClass =
                        currentClass.getSuperclass()) {
                    Collections.addAll(allFields, currentClass.getDeclaredFields());
                }
    
                return new CustomNestedObjectQueryMapEncoder.ObjectParamMetadata(allFields.stream()
                        .filter(field -> !field.isSynthetic())
                        .peek(field -> field.setAccessible(true))
                        .collect(Collectors.toList()));
            }
        }
    }
    

    Usage:

        @Autowired(required = false)
        private SpringDataWebProperties springDataWebProperties;
        
        @Bean
        public QueryMapEncoder feignQueryMapEncoderPageable() {
            PageableSpringQueryMapEncoder queryMapEncoder = new CustomNestedObjectQueryMapEncoder();
            if (springDataWebProperties != null) {
                queryMapEncoder.setPageParameter(springDataWebProperties.getPageable().getPageParameter());
                queryMapEncoder.setSizeParameter(springDataWebProperties.getPageable().getSizeParameter());
                queryMapEncoder.setSortParameter(springDataWebProperties.getSort().getSortParameter());
            }
            return queryMapEncoder;
        }
    
  6. Wuaner commented on Jan 12, 2024

    @Wuaner

    Is this fixed in any followup releases?

  7. OlgaMaciaszek commented on Jan 12, 2024

    @OlgaMaciaszek
    Collaborator

    No, @Wuaner , it's an enhancement that is marked as "help wanted". That means we are not planning to work on it, but we are happy to review community PRs for it if they are submitted.

  8. nikita-kibitkin commented on May 18, 2026

    @nikita-kibitkin

    I'd like to take this. Before any PR, one thing needs settling.

    The flatten itself is straightforward: nested objects to dot notation (range.from=1&range.to=2) and object collections to list[0].field=..., same as the workarounds above. It fits in PageableSpringQueryMapEncoder, so feign-core stays untouched.

    The open question is the opt-in. There's no major release planned, so this has to stay backwards compatible: I'd gate it behind a property defaulting to off, same reasoning as #1013. @OlgaMaciaszek do you want a dedicated property here, or should this build on the @QueryMap mapEncoder attribute from #1013? That direction is the only blocker before I start.

  9. sharanggupta commented on Oct 13, 2026

    @sharanggupta
    Contributor

    I have opened #1448 for this. It follows the direction from the discussion: an opt-in flag, spring.cloud.openfeign.client.nested-query-map-enabled (disabled by default), and no new interface. When it is set, the auto-configured QueryMapEncoder is decorated with a NestedObjectQueryMapEncoder that sends a nested object as range.from=1&range.to=2, the objects of a collection or an array as filters[0].name=status, and the entries of a map as attributes[color]=red, which Spring MVC binds with @ModelAttribute. Collections of simple values are still sent as repeated parameters. The PR includes an end-to-end test against a Spring MVC controller, and the decorator can also wrap a custom QueryMapEncoder.

  10. added this to the 5.1.0-RC2 milestone on Oct 23, 2026
  11. added 2 commits that reference this issue on Oct 23, 2026
    1b13146
    be16f09
  12. moved this from In Progress to Done in 2026.0.0-RC2on Oct 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementhelp wanted

    Type

    No type

    Projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions