Skip to content

Instantly share code, notes, and snippets.

@electrum
Created January 8, 2013 19:18
Show Gist options
  • Save electrum/4487001 to your computer and use it in GitHub Desktop.
Save electrum/4487001 to your computer and use it in GitHub Desktop.
package javatest;
import com.google.common.collect.ImmutableMap;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.type.TypeReference;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public final class JacksonTest
{
public static class MapSerializer
extends JsonSerializer<Map<String, String>>
{
@Override
public void serialize(Map<String, String> value, JsonGenerator jgen, SerializerProvider provider)
throws IOException
{
jgen.writeStartArray();
for (Map.Entry<String, String> entry : value.entrySet()) {
jgen.writeStartObject();
jgen.writeObjectField("key", entry.getKey());
jgen.writeObjectField("value", entry.getValue());
jgen.writeEndObject();
}
jgen.writeEndArray();
}
}
private static class MapDeserializer
extends JsonDeserializer<Map<String, String>>
{
@SuppressWarnings("PublicField")
private static class Entry
{
@JsonProperty public String key;
@JsonProperty public String value;
}
@Override
public Map<String, String> deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException
{
List<Entry> list = jp.readValueAs(new TypeReference<List<Entry>>() {});
ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
for (Entry entry : list) {
map.put(entry.key, entry.value);
}
return map.build();
}
}
public static class Model
{
private final Map<String, String> map;
@JsonCreator
public Model(@JsonProperty("map") @JsonDeserialize(using = MapDeserializer.class) Map<String, String> map)
{
this.map = ImmutableMap.copyOf(map);
}
@JsonProperty
@JsonSerialize(using = MapSerializer.class)
public Map<String, String> getMap()
{
return map;
}
}
public static void main(String[] args)
throws Exception
{
Model original = new Model(Collections.singletonMap("test", "test"));
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(original);
Model deserialized = mapper.readValue(json, Model.class);
System.out.println(json);
System.out.println(original.getMap().equals(deserialized.getMap()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment