代码之家  ›  专栏  ›  技术社区  ›  Bax

Jackson没有使用类注释中指定的自定义反序列化程序

  •  0
  • Bax  · 技术社区  · 3 年前

    Jackson bean配置为使用自定义反序列化程序

    @JsonDeserialize(using = Planet.Deserializer.class)
    public class Planet {
    
      static Map<String, Planet> SINGLETONS = Map.of(
              "EARTH", new Planet("Earth", 1),
              "MARS", new Planet("Mars", 2)
      );
    
      String name;
      // size is here to prevent Jackson from using the constructor
      int size;
    
      Planet(String name, int size) {
        this.name = name;
        this.size = size;
      }
    
      static Planet valueOf(String name) {
        Planet planet = SINGLETONS.get(name);
        if (planet == null) {
          throw new IllegalArgumentException("No Planet by the name " + name + " found");
        }
        return planet;
      }
    
      public String getName() {
        return this.name;
      }
    
      public void setName(String name) {
        this.name = name;
      }
    
      public static class Deserializer extends StdDeserializer<Planet> {
    
        public Deserializer() {
          super((Class<?>) null);
        }
    
        @Override
        public Planet deserialize(JsonParser jsonParser, DeserializationContext ctx) throws IOException {
          final String value = jsonParser.getValueAsString();
          return Planet.valueOf(value.toUpperCase());
        }
      }
    }
    

    Planet工作

    public class Expedition {
      Planet destination;
      public Planet getDestination() {
        return destination;
      }
      public void setDestination(Planet destination) {
        this.destination = destination;
      }
    }
    // custom deserializer is used
    new ObjectMapper().readValue("{\"destination\":\"mars\"}", Expedition.class)
    

    列表<星球>作品

    public class Expedition {
      List<Planet> list;
      public List<Planet> getList() {
        return this.list;
      }
      public void setList(List<Planet> list) {
        this.list = list;
      }
    }
    // custom deserializer is used
    new ObjectMapper().readValue("{\"list\":[\"mars\"]}", Expedition.class)
    

    映射<行星,字符串>不起作用

    public class Expedition {
      private Map<Planet, String> map;
      public Map<Planet, String> getMap() {
        return this.map;
      }
      public void setMap(Map<Planet, String> map) {
        this.map = map;
      }
    }
    // custom deserializer is not used, invokes valueOf directly instead
    new ObjectMapper().readValue("{\"map\":{\"mars\" : \"a\"}}", Expedition.class)
    

    当类用作Map键时,为什么Jackson不使用自定义反序列化程序?

    该问题的解决方案:

    我通过使用解决了这一问题 @JsonDeserialize(keyUsing = ...) 在远征班

    jackson数据绑定2.15.2

    0 回复  |  直到 3 年前