Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

前端 未结 5 1661
谎友^
谎友^ 2020-11-30 04:41

I have a REST service built with Jersey and deployed in the AppEngine. The REST service implements the verb PUT that consumes an application/json media type. Th

相关标签:
5条回答
  • 2020-11-30 04:52

    This is the solution for my old question:

    I implemented my own ContextResolver in order to enable the DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature.

    package org.lig.hadas.services.mapper;
    
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.ext.ContextResolver;
    import javax.ws.rs.ext.Provider;
    
    import org.codehaus.jackson.map.DeserializationConfig;
    import org.codehaus.jackson.map.ObjectMapper;
    
    @Produces(MediaType.APPLICATION_JSON)
    @Provider
    public class ObjectMapperProvider implements ContextResolver<ObjectMapper>
    {
       ObjectMapper mapper;
    
       public ObjectMapperProvider(){
           mapper = new ObjectMapper();
           mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
       }
       @Override
       public ObjectMapper getContext(Class<?> type) {
           return mapper;
       }
    }
    

    And in the web.xml I registered my package into the servlet definition...

    <servlet>
        <servlet-name>...</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>...;org.lig.hadas.services.mapper</param-value>        
        </init-param>
        ...
    </servlet>
    

    ... all the rest is transparently done by jersey/jackson.

    0 讨论(0)
  • 2020-11-30 04:59

    Setting this attribute to ObjectMapper instance works,

    objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
    
    0 讨论(0)
  • 2020-11-30 05:03

    do you try

    [{"name":"myEnterprise", "departments":["HR"]}]
    

    the square brace is the key point.

    0 讨论(0)
  • 2020-11-30 05:08

    For people that find this question by searching for the error message, you can also see this error if you make a mistake in your @JsonProperty annotations such that you annotate a List-typed property with the name of a single-valued field:

    @JsonProperty("someSingleValuedField") // Oops, should have been "someMultiValuedField"
    public List<String> getMyField() { // deserialization fails - single value into List
      return myField;
    }
    
    0 讨论(0)
  • 2020-11-30 05:11

    from Jackson 2.7.x+ there is a way to annotate the member variable itself:

     @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
     private List<String> newsletters;
    

    More info here: Jackson @JsonFormat

    0 讨论(0)
提交回复
热议问题