OK, so, the question states it correctly : it is not possible to use JSON maps in which keys are not strings. As a consequence, to emulate the Java Map in javascript, one has to go a longer path, which would typically involve transforming the map into ... something else.
What I chose was the quite usual array of arrays :
a map such as
{
a:b,
c:d,
}
Will then be translated into the array
[
[a,b],
[c,d],
]
What are the detailled steps required to obtain that result
Configure custom (de)serialization
This is obtained by setting a serialization factory into the object mapper, as Jackson doc clearly explains :
/**
* Associates all maps with our custom serialization mechanism, which will transform them into arrays of arrays
* @see MapAsArraySerializer
* @return
*/
@Produces
public SerializerFactory createSerializerFactory() {
CustomSerializerFactory customized = new CustomSerializerFactory();
customized.addGenericMapping(Map.class, new MapAsArraySerializer());
return customized;
}
public @Produces ObjectMapper createMapper() {
ObjectMapper jsonMapper = new ObjectMapper();
// ....
// now configure serializer
jsonMapper.setSerializerFactory(createSerializerFactory());
// ....
return jsonMapper;
}
The process seems quite simple, mainly because serialization provides quite correct polymorphism features in serialization, which are not that good for deserialization. Indeed, as doc also states, deserialization requires adding explicit class mappings, which are not used in any object-oriented fashion (inheritence is not supported there)
/**
* Defines a deserializer for each and any used map class, as there is no inheritence support ind eserialization
* @return
*/
@Produces
public DeserializerProvider createDeserializationProvider() {
// Yeah it's not even a standard Jackson class, it'll be explained why later
CustomDeserializerFactory factory = new MapAsArrayDeserializerFactory();
List<Class<? extends Map>> classesToHandle = new LinkedList<>();
classesToHandle.add(HashMap.class);
classesToHandle.add(LinkedHashMap.class);
classesToHandle.add(TreeMap.class);
for(Class<? extends Map> c : classesToHandle) {
addClassMappingFor(c, c, factory);
}
// and don't forget interfaces !
addClassMappingFor(Map.class, HashMap.class, factory);
addClassMappingFor(SortedMap.class, TreeMap.class, factory);
return new StdDeserializerProvider(factory);
}
private void addClassMappingFor(final Class<? extends Map> detected, final Class<? extends Map> created, CustomDeserializerFactory factory) {
factory.addSpecificMapping(detected, new MapAsArrayDeserializer() {
@Override
protected Map createNewMap() throws Exception {
return created.newInstance();
}
});
}
// It's the same createMapper() method that was described upper
public @Produces ObjectMapper createMapper() {
ObjectMapper jsonMapper = new ObjectMapper();
// ....
// and deserializer
jsonMapper.setDeserializerProvider(createDeserializationProvider());
return jsonMapper;
}
Now we have correctly defined how (de)serialization is customized, or do we have ? In fact, no : the MapAsArrayDeserializerFactory
deserves its own explanation.
After some debugging, I found that DeserializerProvider
delegates to the DeserializerFactory
when no deserializer exists for class, which is cool. But, the DeserializerFactory
creates the deserializer according to the "kind" of obejct : if it is a collection, then a CollectionDeserializer will be used (to read the array into a Collection). If it's a Map, then the MapDeserializer will be used.
Unfortunatly, this resolution uses the java class given in the JSON stream (especially when using polymorphic deserialization, which was my case). As a consequence, configuring custom deserialization has no effect, unless the CustomDeserializerFactory
is customized ... like that :
public class MapAsArrayDeserializerFactory extends CustomDeserializerFactory {
@Override
public JsonDeserializer<?> createMapDeserializer(DeserializationConfig config, MapType type, DeserializerProvider p) throws JsonMappingException {
return createBeanDeserializer(config, type, p);
}
}
Yup, i deserialize all maps as beans. But now, all my deserializers are correctly called.
Serializing
Now, serialization is a rather simple task :
public class MapAsArraySerializer extends JsonSerializer<Map> {
@SuppressWarnings("unchecked")
private Set asListOfLists(Map<?, ?> value) {
Set returned = new HashSet<>();
for(Map.Entry e : value.entrySet()) {
returned.add(Arrays.asList(e.getKey(), e.getValue()));
}
return returned;
}
@Override
public void serialize(Map value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
Collection entries = asListOfLists(value);
jgen.writeObjectField("entries", entries);
}
@Override
public void serializeWithType(Map value, JsonGenerator jgen, SerializerProvider provider, TypeSerializer typeSer) throws IOException,
JsonProcessingException {
Collection entries = asListOfLists(value);
typeSer.writeTypePrefixForObject(value, jgen);
jgen.writeObjectField("entries", entries);
typeSer.writeTypeSuffixForObject(value, jgen);
}
}
Deserialization
And deserialization is not more complex :
public abstract class MapAsArrayDeserializer<Type extends Map> extends JsonDeserializer<Type> {
protected Type newMap(Collection c, Type returned) {
for(Object o : c) {
if (o instanceof List) {
List l = (List) o;
if(l.size()==2) {
Iterator i = l.iterator();
returned.put(i.next(), i.next());
}
}
}
return returned;
}
protected abstract Type createNewMap() throws Exception;
@Override
public Type deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
if(jp.getCurrentToken().equals(JsonToken.START_OBJECT)) {
JsonToken nameToken = jp.nextToken();
String name = jp.getCurrentName();
if(name.equals("entries")) {
jp.nextToken();
Collection entries = jp.readValueAs(Collection.class);
JsonToken endMap = jp.nextToken();
try {
return newMap(entries, createNewMap());
} catch(Exception e) {
throw new IOException("unable to create receiver map", e);
}
} else {
throw new IOException("expected \"entries\", but field name was \""+name+"\"");
}
} else {
throw new IOException("not startying an object ? Not possible");
}
}
@Override
public Type deserializeWithType(JsonParser jp, DeserializationContext ctxt, TypeDeserializer typeDeserializer) throws IOException,
JsonProcessingException {
Object value = typeDeserializer.deserializeTypedFromObject(jp, ctxt);
return (Type) value;
}
}
Well, expected the class is left abstract t have each declared subtype create the right map instance.
And now
And now it works seamlessly on Java side (cause the Javascript has to have a map-equivalent object to read those datas.