Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

json - Deserialize ArrayList from String using Jackson

I am using Spring's MappingJacksonHttpMessageConverter to convert JSON message to object in my controller.

<bean id="jsonConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="prefixJson" value="false" />
    <property name="supportedMediaTypes" value="application/json" />
</bean>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonConverter" />
        </list>
    </property>
</bean>

For fields that are declared as ArrayList, if the json message contains a String instead, the following exception will be thrown:

org.springframework.http.converter.HttpMessageNotReadableException: 
 Could not read JSON: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token

An example would be the class definition below:

public class Product {
   private String name;
   private List<String> images;
}

Where the incoming Json is:

{name:"Widget", images:"image1.jpg"}

AS you can see, this will produce the exception since image is expected to be an array.

I would like to make custom deserializer which is a bit more tolerant. If deserialization fails, create a ArrayList of a single element from the String. How would I go about injecting this into the MappingJacksonHttpMessageConverter or ObjectMapper?

I am not looking to use annotation to mark each and every ArrayList field so a custom deserialize could be used. I am looking for a way to overwrite the default deserializer to preform this function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Check out this article describing how to use the features of the jackson objectMapper to accomplish this.

https://github.com/FasterXML/jackson-dataformat-xml/issues/21

For me adding the following solved this issue

jsonMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...