Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fasterxml serialize using toString and deserialize using String constructor

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?

like image 726
PaddyD Avatar asked Jul 22 '15 16:07

PaddyD


1 Answers

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() ...

}
like image 73
PaddyD Avatar answered Sep 24 '22 10:09

PaddyD