如何用jackson将map< key,value>转换成{“keyprop”:key,“valueprop”:value}数组?

i7uaboj4  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(325)

我正在努力做到以下几点
鉴于

Map<String, String> labels = {"en_GB" : "English", "de" : "German", "it" : "Italian"}....

我想用jackson把它序列化到

[{"language" : "en_GB", "label" : "English"}, {"language" : "de", "label" : "German"}, {"language" : "it", "label" : "Italian"}]

本质上,将Map拆分为对象数组,键和值作为单独的属性
而不是

{"en_GB" : "English", "de" : "German", "it" : "Italian"}

我搜遍了Jackson所有的文件,却找不到答案。我会很感激你的帮助。提前谢谢!

eulz3vhy

eulz3vhy1#

方法1:定义一个中间pojo,并将map<string,string>转换为中间对象列表
首先定义一个中间pojo:

public class LanguageInfo {
    private String language;
    private String label;
}

将Map转换为中间pojo的列表,并将列表序列化为字符串:

Map<String, String> labels = new HashMap<>();
labels.put("en_GB", "English");
labels.put("de", "German");
labels.put("it", "Italian");

List<LanguageInfo> languageInfoList = labels.entrySet().stream()
  .map(entry -> {
      LanguageInfo info = new LanguageInfo();
      info.setLabel(entry.getValue());
      info.setLanguage(entry.getKey());
      return info;
  }).collect(Collectors.toList());
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(languageInfoList));

输出为:

[
    {
        "language":"de",
        "label":"German"
    },
    {
        "language":"en_GB",
        "label":"English"
    },
    {
        "language":"it",
        "label":"Italian"
    }
]

方法2:定义 JsonSerializer 并使用它进行序列化工作
假设要直接序列化以下类:

@Data
public class LanguageInfos {
    private Map<String, String> labels;
}

首先,定义一个 JsonSerializer 序列化 LanguageInfos :
需要中间的pojo LanguageInfo 上述定义:

public class LanguageInfosJsonSerializer extends JsonSerializer<LanguageInfos> {

    @Override
    public void serialize(LanguageInfos languageInfos, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        // LanguageInfo defined in below code
        List<LanguageInfo> languageInfoList = languageInfos.getLabels().entrySet().stream()
            .map(entry -> {
                LanguageInfo info = new LanguageInfo();
                info.setLabel(entry.getValue());
                info.setLanguage(entry.getKey());
                return info;
            }).collect(Collectors.toList());
        jsonGenerator.writeObject(languageInfoList);
    }
}

不需要中间的pojo:

public class LanguageInfosJsonSerializer extends JsonSerializer<LanguageInfos> {

    @Override
    public void serialize(LanguageInfos languageInfos, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeStartArray(languageInfos.getLabels().size());
        languageInfos.getLabels().entrySet().forEach(new Consumer<Map.Entry<String, String>>() {
            @SneakyThrows
            @Override
            public void accept(Map.Entry<String, String> entry) {
                    ObjectNode node = new ObjectMapper().createObjectNode();
                    node.put("language",entry.getKey());
                    node.put("label",entry.getValue());
                    jsonGenerator.writeObject(node);
            }
        });
        jsonGenerator.writeEndArray();
    }
}

其次,将此序列化程序注册到objectmapper对象:

SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(LanguageInfos.class, new LanguageInfosJsonSerializer());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(simpleModule);

第三,直接使用objectmapper序列化:

Map<String, String> labels = new HashMap<>();
labels.put("en_GB", "English");
labels.put("de", "German");
labels.put("it", "Italian");

LanguageInfos languageInfos = new LanguageInfos();
languageInfos.setLabels(labels);

ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(LanguageInfos.class, new LanguageInfosJsonSerializer());
mapper.registerModule(simpleModule);
System.out.println(mapper.writeValueAsString(languageInfos));

输出为:

[
    {
        "language":"de",
        "label":"German"
    },
    {
        "language":"en_GB",
        "label":"English"
    },
    {
        "language":"it",
        "label":"Italian"
    }
]

相关问题