使用toString进行rapidxml序列化并使用String构造函数进行反序列化 [英] fasterxml serialize using toString and deserialize using String constructor

查看:273
本文介绍了使用toString进行rapidxml序列化并使用String构造函数进行反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个POJO,看起来像这样:

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

}

我想用它作为地图的关键(例如 HashMap< Thing,SomeOtherPOJO> ),当序列化为json时,使用Thing的toString()表示作为键,并且在反序列化时使用String构造函数。这可能是使用像jackson数据绑定注释这样简单的东西吗?解决这个问题的最佳方法是什么?

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?

推荐答案

通过实验(我认为文档可能会更加清晰)我发现我可以在 String 构造函数和 JsonValue <上使用 JsonCreator 注释/ code>在 toString()方法上实现我想要的:

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

}

这篇关于使用toString进行rapidxml序列化并使用String构造函数进行反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆