【问题标题】:How to map multiple different request bodies in to same POJO using a configuration file如何使用配置文件将多个不同的请求主体映射到同一个 POJO
【发布时间】:2019-03-13 00:37:07
【问题描述】:

我有不同的帖子请求正文,如下所示:

{
   "name": "US",  
   "amount": "1234"    
}

{
   "fullName": "US",  
   "transAmount": "1234"    
}

我创建了一个 java 过滤器来修改我的 Spring Boot 应用程序中的那些请求主体。我想将它们转换为统一格式,以使所有请求主体都可以映射到同一个 POJO。

最终“name”和“fullName”应该被映射到name, “amount”和“transAmount”应该映射到amount。我怎样才能做到这一点?

我已经有了答案:

@JsonAlias({"name", "fullName"})
private String name; 

但我想使用配置文件来实现这一点。然后只需更改配置文件,我就可以添加/删除映射值。如何使用配置文件做同样的事情?

【问题讨论】:

    标签: java json spring-boot http-post mapping


    【解决方案1】:

    可能的解决方案。 (我相信可能有其他替代品)

    我猜你需要覆盖默认的JacksonAnnotationIntrospector 的行为,并在findPropertyAliases(..) 方法中实现你的自定义逻辑。

    然后可以使用ObjectMapper#setAnnotationIntrospector 调用注册您的(自定义)内省。

    public void tryIt() throws IOException
    {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setAnnotationIntrospector(new CustomAnnotationIntrospector());
    
        YourBean yourBean = objectMapper.readValue("{\"altField\": \"abc\"}", YourBean.class);
        System.out.println(yourBean.getField());
    }
    
    static class YourBean
    {
        @JsonAliasConfigPath("/some/where")
        private String field;
    
        public String getField()
        {
            return field;
        }
    
        public void setField(String field)
        {
            this.field = field;
        }
    }
    
    
    @Target({ElementType.ANNOTATION_TYPE,
            ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER
    })
    @Retention(RetentionPolicy.RUNTIME)
    @JacksonAnnotation
    @interface JsonAliasConfigPath
    {
    
        String value();
    
    }
    
    
    class CustomAnnotationIntrospector extends JacksonAnnotationIntrospector
    {
        @Override
        public List<PropertyName> findPropertyAliases(Annotated member)
        {
            CustomAliasConfig.JsonAliasConfigPath atConfigPath = _findAnnotation(member, CustomAliasConfig.JsonAliasConfigPath.class);
    
            if (atConfigPath != null)
            {
                // here is your config file
                String value = atConfigPath.value();
                String setterName = member.getName();
                // read&return aliases for setterName
                // return youListOfAliases;
    
                // let`s assume it turns your member should be expected as "altField"
                return Arrays.asList(PropertyName.construct("altField"));
            }
    
            return super.findPropertyAliases(member);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-12
      • 1970-01-01
      • 2019-02-04
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多