如何使用Jackson将地图序列化为列表 [英] How to Serialize a Map as List using Jackson

查看:209
本文介绍了如何使用Jackson将地图序列化为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将作为Map的值的属性序列化为Map的值?我已经能够使用getter上的 @JsonSerialize(using = ...)注释进行其他简单的转换。但是,我不确定是否存在我想要做的事情。

How can I serialize a property which is a Map as a List of the Map's values? I've been able to do other simple conversions using the @JsonSerialize(using=...) annotation on the getter. However, I am not sure if one exists for what I want to do.

推荐答案

我们需要类似的东西,在我们的例子中我们你评论时使用了一个自定义的 @JsonSerialize ,这很简单:

We needed something similar, in our case we used a customized @JsonSerialize as you commented, and it was stupid simple:

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")));
    }

}

这篇关于如何使用Jackson将地图序列化为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆