AdamSpurgin
AdamSpurgin

Reputation: 961

Json serialization of a simple map is causing stackOverflowErrors

This simple code:

public static void Test() throws JsonProcessingException {
    Map<Object, Object> request = new HashMap<>();
    request.put("id", "test_0001");
    request.put("version", 1);

    Map<Object, Object> fields = new HashMap<>();
    fields.put("uri", "blah/blah");
    fields.put("owner", "me");

    request.put("fields", request);

    ObjectMapper om = new ObjectMapper();
    System.out.println(om.writeValueAsString(request));
}

Is causing this exception:

Exception in thread "main" java.lang.StackOverflowError
    at java.lang.Enum.ordinal(Enum.java:103)
    at com.fasterxml.jackson.databind.MapperFeature.getMask(MapperFeature.java:259)
    at com.fasterxml.jackson.databind.cfg.MapperConfig.isEnabled(MapperConfig.java:110)
    at com.fasterxml.jackson.databind.SerializationConfig.getAnnotationIntrospector(SerializationConfig.java:404)
    at com.fasterxml.jackson.databind.SerializerProvider.getAnnotationIntrospector(SerializerProvider.java:307)
    at com.fasterxml.jackson.databind.ser.std.MapSerializer.createContextual(MapSerializer.java:235)
    at com.fasterxml.jackson.databind.SerializerProvider._handleContextual(SerializerProvider.java:968)
    at com.fasterxml.jackson.databind.SerializerProvider.findValueSerializer(SerializerProvider.java:447)
    at com.fasterxml.jackson.databind.ser.impl.PropertySerializerMap.findAndAddSerializer(PropertySerializerMap.java:38)
    at com.fasterxml.jackson.databind.ser.std.MapSerializer._findAndAddDynamic(MapSerializer.java:516)
    at com.fasterxml.jackson.databind.ser.std.MapSerializer.serializeFields(MapSerializer.java:386)
    at com.fasterxml.jackson.databind.ser.std.MapSerializer.serialize(MapSerializer.java:312)
    at com.fasterxml.jackson.databind.ser.std.MapSerializer.serialize(MapSerializer.java:26)
etc...

And for the life of me I cant figure out why. All I have found with by searching is people having issues because of recursive references, but that's not the case in this instance.

Upvotes: 0

Views: 2016

Answers (2)

Boris the Spider
Boris the Spider

Reputation: 61168

You have put a Map into itself

request.put("fields", request);

This makes an infinite loop. You shouldn't put the Map into itself.

You probably meant to write

request.put("fields", fields);

Upvotes: 7

Lee Meador
Lee Meador

Reputation: 12985

This line creates a loop in the data:

request.put("fields", request);

This is exactly what a recursive reference looks like.

Upvotes: 2

Related Questions