简体   繁体   English

Jackson定制序列化获取器

[英]Jackson custom serialization getter

Let's say I have a POJO like: 假设我有一个像这样的POJO:

public class User {
     private Long id;
     private String username;

     // usual getters and setters
     ....

     // only for serialisation purposes
     public String getUpperUsername() {
         return this.id % 2 == 0 ? username : username.toUpperCase();
     }


}

I would like to make a conditional serializer so that it serialises a different value that the actual one if some conditions are satisfied. 我想做一个有条件的序列化程序,以便在满足某些条件的情况下序列化一个与实际值不同的值。

I looked at @JsonGetter but apparently it's deprecated, @JsonProperty doesn't seem to work. 我查看了@JsonGetter,但显然它已被弃用,@ JsonProperty似乎不起作用。

Do you have any idea? 你有什么主意吗?

Thank you in advance :) 先感谢您 :)

@JsonProperty works actually for me when I use it like this: 当我像这样使用@JsonProperty时,它实际上对我有用:

public class User {
      private Long id;
      private String username;

      public Long getId() {
         return id;
      }

      public void setId(Long id) {
         this.id = id;
      }

      public String getUsername() {
         return username;
      }

      public void setUsername(String username) {
         this.username = username;
      }

      @JsonProperty("username")
      public String getUppercaseUsername() {
         return this.id % 2 == 0 ? username : username.toUpperCase();
      }
}

See a test example here . 在此处查看测试示例。

You can also go for a custom serializer, like here if you want to separate this uppercasing logic from the entity itself. 您还可以使用自定义序列化程序,例如如果您要将这种大写逻辑与实体本身分开,就可以在这里进行。

The truth however is that this a business logic, which should not be handled by a serializer - this is a design failure. 但是,事实是这是业务逻辑,不应由序列化程序处理-这是设计失败。 Instead map the username elsewhere and use Jackson only for serialization - it's the purpose of this library. 而是将用户名映射到其他位置,并将Jackson仅用于序列化-这是该库的目的。

You could try to write custom serializer implementing JsonSerializer and using @JsonSerialize then: http://www.baeldung.com/jackson-custom-serialization 您可以尝试编写实现JsonSerializer并使用@JsonSerialize的自定义序列化器,然后: http : //www.baeldung.com/jackson-custom-serialization
But it seems like overkill. 但这似乎太过分了。

Also, if it is acceptable, you could try to put logic of getUpperUsername() in usual getter. 另外,如果可以接受,则可以尝试将getUpperUsername()的逻辑放入常规的getter中。

PS: Strange that @JsonProperty does not work, it match here. PS:奇怪@JsonProperty不起作用,它在这里匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM