title: Serialization of Keys with Circular References using Jackson
body: <p>I am trying to serialize a HashMap from Objects to Strings, but the specific Object has a reference to the current class leading to an infinite recursion, which doesn't seem to be solved with the usual JsonIdentifyInfo annotation. Here's an example:</p>
  
  <pre><code>public class CircularKey {
  
      public void start() throws IOException {
          ObjectMapper mapper = new ObjectMapper();
  
          Cat cat = new Cat();
  
          // Encode
          String json = mapper.writeValueAsString(cat);
          System.out.println(json);
  
          // Decode
          Cat cat2 = mapper.readValue(json, Cat.class);
          System.out.println(mapper.writeValueAsString(cat2));
      }
  }
  
  @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
  @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
  class Mouse {
      int id;
  
      @JsonProperty
      Cat cat;
  }
  
  @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
  @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
  class Cat {
      int id;
  
      @JsonSerialize(keyUsing = MouseMapKeySerializer.class)
      @JsonDeserialize(keyUsing = MouseMapKeyDeserializer.class)
      @JsonProperty
      HashMap&lt;Mouse, String&gt; status = new HashMap&lt;Mouse, String&gt;();
  
      public Cat() {
          Mouse m = new Mouse();
          m.cat = this;
          status.put(m, "mike");
      }
  
  }
  </code></pre>
  
  <p>Here's the serializer/deserializer for the key:</p>
  
  <pre><code>class MouseMapKeySerializer extends JsonSerializer&lt;Mouse&gt; {
  static ObjectMapper mapper = new ObjectMapper();
  
  @Override
  public void serialize(Mouse value, JsonGenerator generator,
          SerializerProvider provider) throws IOException,
          JsonProcessingException {
      String json = mapper.writeValueAsString(value);
      generator.writeFieldName(json);
  }
  }
  
  class MouseMapKeyDeserializer extends KeyDeserializer {
  static ObjectMapper mapper = new ObjectMapper();
  
  @Override
  public Mouse deserializeKey(String c, DeserializationContext ctx)
          throws IOException, JsonProcessingException {
      return mapper.readValue(c, Mouse.class);
  }
  }
  </code></pre>
  
  <p>If I switch the map to HashMap (String,Object) it works but I cannot change the original mapping. Any ideas?</p>