How to pass parameter to JsonSerializer?

大城市里の小女人 提交于 2019-12-03 00:35:18
macko

I know that this is not a new question but here is what I came up with facing the similar problem:

  1. created custom annotation:

    @Target({ ElementType.FIELD, ElementType.TYPE, ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface JsonLocalizable {
    
      public String localizationKey();
    } 
    
  2. Jackson serializer:

     public class LocalizingSerializer extends StdSerializer<String> implements ContextualSerializer {
    
          private String localizationKey;
    
          public LocalizingSerializer() {
            super(String.class);
          }
    
          public LocalizingSerializer(String key) {
            super(String.class);
    
            this.localizationKey = key;
          }
    
          @Override
          public void serialize(String value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
    
            String localizedValue = //.... get the value using localizationKey
    
            jgen.writeString(localizedValue);
          }
    
          @Override
          public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
    
            String key = null;
            JsonLocalizable ann = null;
    
            if (property != null) {
              ann = property.getAnnotation(JsonLocalizable.class);
            }
    
            if (ann != null) {
              key = ann.localizationKey();
            }
    
            //if key== null??
    
            return new LocalizingSerializer(key);
          }
        }
    
  3. Annotate the field you want to localize:

    public class TestClass {
    
        @JsonSerialize(using = LocalizingSerializer.class)
        @JsonLocalizable(localizationKey = "my.key")
        private String field;
    
        public String getField() {
          return this.field;
        }
    
        public void setField(String field) {
          this.field = field;
        }
    }
    

Solution 1. In your JAX-RS implementation register your own implementation of MessageBodyWriter for JSON requests. Probably your implementation will extend Jackson. Also it might be possible that you will have to unregister Jackson. In a MessageBodyWriter you can inject a UriInfo instance using the @Context annotation, and with it you can get any request parameter.

Solution 2. Change the architecture of your Data, so that it is locale-aware. For example, create a setter setLocale() which will change the returned data, if the locale was set.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!