在Spring MVC中使用Jackson将地图序列化为一对夫妇 [英] Serialize a Map into an array of couple using Jackson in Spring MVC

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

问题描述

首先,我知道我想做的事可以使用自定义的JsonSerializer完成,但是我想知道是否为此目的提供了更少的样板代码解决方案.

First of all, I know what I am trying to do can be done using a custom JsonSerializer, but I'd like to know whether there is a less boilerplate code solution for this.

Spring MVC中,我想将Map序列化为夫妇列表.假设我想返回这样的Map:

In Spring MVC, I'd like to serialize a Map into a list of couples. Let's say I'd like to return such a Map:

Map<String, String> res = new HashMap<>();
res.put("key1", "value1");
res.put("key2", "value2");

默认的序列化结果将给出如下所示的JSON:

The default serialization result will give a JSON like this:

{key1: value1, key2: value2}

是否有一种无需使用自定义JsonSerializer即可拥有类似内容的方法?

Is there a way to have instead something like this, without using a custom JsonSerializer?

[{key: "key1", value: "value1"}, {key: "key2", value: "value2"}]

我正在使用Spring-Boot 1.3,其默认版本为Spring MVCJackson.

I'm using Spring-Boot 1.3 with default versions of Spring MVC and Jackson.

推荐答案

由于我更喜欢​​可重用的解决方案,并且找不到标准的解决方案,因此我使用自定义的JsonSerializer来实现它,如下所示:

As I prefered a reusable solution, and could not find a standard solution, I implemented it with a custom JsonSerializer, as follows:

public class MapToCoupleArraySerializer extends JsonSerializer<Map<?, ?>>{

    @Override
    public void serialize(Map<?, ?> value, JsonGenerator generator,
            SerializerProvider serializers) throws IOException,
            JsonProcessingException {
        generator.writeStartArray();
        for (Entry<?, ?> entry : value.entrySet()){
            generator.writeStartObject();
            generator.writeObjectField("key", entry.getKey());
            generator.writeObjectField("value", entry.getValue());
            generator.writeEndObject();
        }       
        generator.writeEndArray();
    }    
}

并以传统的Spring方式使用它:

and use it in the traditionnal Spring way:

public class MyClassToSerialize{

    @JsonSerialize(using = MapToCoupleArraySerializer .class)
    private Map<Key, Value> recipes;

    // ...
}

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

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