Reputation: 2322
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.
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");
The default serialization result will give a JSON
like this:
{key1: value1, key2: value2}
Is there a way to have instead something like this, without using a custom JsonSerializer
?
[{key: "key1", value: "value1"}, {key: "key2", value: "value2"}]
I'm using Spring-Boot 1.3
with default versions of Spring MVC
and Jackson
.
Upvotes: 6
Views: 4973
Reputation: 2322
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();
}
}
and use it in the traditionnal Spring
way:
public class MyClassToSerialize{
@JsonSerialize(using = MapToCoupleArraySerializer .class)
private Map<Key, Value> recipes;
// ...
}
Upvotes: 10
Reputation: 2043
try to serialize entries
instead of the map itself :
Map.Entry[] entries = myMap.entrySet().toArray(new Map.Entry[]{});
I didn't try it, but the result should be similar enough to what you want.
Upvotes: 3