小编典典

如何使用Jackson将地图序列化为列表

java

如何将作为地图的属性序列化为地图的值列表?我已经能够使用@JsonSerialize(using=...)吸气剂上的注释进行其他简单的转换。但是,我不确定我想做什么。


阅读 223

收藏
2020-11-16

共1个答案

小编典典

我们需要类似的东西,在我们的案例中,我们使用了@JsonSerialize您所评论的自定义项,这很简单:

public class MyCustomSerializer extends JsonSerializer<Map<?, ?>> {
    @Override
    public void serialize(final Map<?, ?> value, final JsonGenerator jgen, final SerializerProvider provider)
            throws IOException, JsonProcessingException {
        jgen.writeObject(value.values());
    }
}

使用它的代码:

import java.io.IOException;
import java.util.Collections;
import java.util.Map;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.annotate.JsonSerialize;

public class JacksonTest {

    public static class ModelClass {
        private final Map<String, String> map;

        public ModelClass(final Map<String, String> map) {
            super();
            this.map = map;
        }

        @JsonSerialize(using = MyCustomSerializer.class)
        public Map<String, String> getMap() {
            return map;
        }

    }

    public static void main(final String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(System.out, new ModelClass(Collections.singletonMap("test", "test")));
    }

}
2020-11-16