fasterxml serialize using toString and deserialize using String constructor

PaddyD picture PaddyD · Jul 22, 2015 · Viewed 9k times · Source

I have a POJO which looks something like this:

public class Thing
{
   private final int x;
   private final int y;
   private final int z;

   public Thing(String strThing)
   {
       // parse strThing which is in some arbitrary format to set x, y and z
   }

   @Override
   public String toString()
   {
       // return a string representation of thing
       // (same format as that parsed by the constructor)
   }

   @Override
   public boolean equals(Object obj) ...

   @Override
   public int hashCode() ...

}

and I want to use it as a key for a map (e.g. HashMap<Thing, SomeOtherPOJO>) which, when serializing to json, uses the toString() representation of Thing for the key, and when deserializing, uses the String constructor. Is this possible using something simple like jackson databind annotations? What would be the best way to tackle this?

Answer

PaddyD picture PaddyD · Jul 23, 2015

Through experimentation (I think the documentation could have been a little clearer on this) I have discovered that I can use the JsonCreator annotation on the String constructor and JsonValue on the toString() method to achieve what I want:

public class Thing
{
   private final int x;
   private final int y;
   private final int z;

   @JsonCreator
   public Thing(String strThing)
   {
       // parse strThing which is in some arbitrary format to set x, y and z
   }

   @Override
   @JsonValue
   public String toString()
   {
       // return a string representation of thing
       // (same format as that parsed by the constructor)
   }

   @Override
   public boolean equals(Object obj) ...

   @Override
   public int hashCode() ...

}