Jersey: Json array with 1 element is serialized as object

前端 未结 8 2174
眼角桃花
眼角桃花 2021-01-03 19:20

I\'m creating a REST server with Jersey/Java and I found a strange behavior.

I have a method on the server that returns an array of objects as Json

@         


        
8条回答
  •  失恋的感觉
    2021-01-03 19:45

    Converting the Array into ArrayList would suffice the requirement here. Similar kind of contradictory issue I have faced, where I had to return the Json Array Object instead of list in case of single element.

    There i took the help of below annotation to get my job done-

    @JsonFormat(with = JsonFormat.Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED). Below is the example of a JSON Pojo class:

    import java.util.List;
    
    import com.fasterxml.jackson.annotation.JsonFormat;
    import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
    import com.fasterxml.jackson.annotation.JsonProperty;
    
    @JsonIgnoreProperties(ignoreUnknown = true)
    public class TAResponseMapper {
    
        @JsonProperty("Response")
        @JsonFormat(with = JsonFormat.Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED) 
        private List responses;
    
        public List getResponses() {
            return responses;
        }
    
        public void setResponses(List responses) {
            this.responses = responses;
        }
    
    }
    

提交回复
热议问题