Created
August 22, 2019 09:00
-
-
Save talalUcef/8a78d09477e5b07f57c7738297a8b8a9 to your computer and use it in GitHub Desktop.
Jackson Map to Array serialisation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.red.bol.serializer; | |
import com.fasterxml.jackson.core.JsonGenerator; | |
import com.fasterxml.jackson.databind.JsonSerializer; | |
import com.fasterxml.jackson.databind.SerializerProvider; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import java.io.IOException; | |
import java.util.Map; | |
public class MapToArraySerializer extends JsonSerializer<Map<?, ?>> { | |
private static final Logger LOGGER = LoggerFactory.getLogger(MapToArraySerializer.class); | |
@Override | |
public void serialize(Map<?, ?> map, JsonGenerator generator, SerializerProvider serializers) throws IOException { | |
generator.writeStartArray(); | |
map.forEach((key, value) -> { | |
try { | |
generator.writeStartObject(); | |
generator.writeObjectField(key.toString(), value); | |
generator.writeEndObject(); | |
} catch (IOException e) { | |
LOGGER.error("Cannot serialize entry with key {} and value {}", key, value); | |
} | |
}); | |
generator.writeEndArray(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@JsonSerialize(using = MapToArraySerializer.class) | |
private Map<?,?> items; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment