【问题标题】:How to access the gson SerializedName annotaion value from properties file如何从属性文件访问 gson SerializedName 注释值
【发布时间】:2021-07-06 15:18:46
【问题描述】:

我正在尝试将我的 json 字符串反序列化为我的自定义类,我想制作 @SerializedName 注释值作为可配置参数访问,该参数应从应用程序属性文件中读取值。我提供了以下代码 sn-p,但它接受一个常量字符串,有没有其他方法可以使这些参数成为可配置的

    {
  FName: "Sample",
  LName: "LName"}

 class Test{
     
@SerializedName(value=${"${name}"})
    private string name;
@SerializedName(value=${"${data}"})
    private string data;
}

application.properties file
name=FName
data=LName

【问题讨论】:

  • Gson 不支持占位符,所以你不能这样做。
  • 为什么不使用 Spring 中的 @Value?
  • 我尝试了@Value,但即使这样也没有用

标签: java spring gson


【解决方案1】:

Gson 不知道任何其他库,除非你告诉它这样做(为什么要为你可能永远不会使用的东西付费?)。您可以使用 FieldNamingStrategy 接口的自定义实现在 Gson 提供的基础上扩展 Gson:

public final class ValueFieldNamingStrategy
        implements FieldNamingStrategy {

    private final Environment environment;

    private ValueFieldNamingStrategy(final Environment environment) {
        this.environment = environment;
    }

    public static FieldNamingStrategy of(final Environment environment) {
        return new ValueFieldNamingStrategy(environment);
    }

    @Override
    public String translateName(final Field f) {
        @Nullable
        final Value valueAnnotation = f.getAnnotation(Value.class);
        if ( valueAnnotation == null ) {
            return f.getName();
        }
        return environment.resolvePlaceholders(valueAnnotation.value());
    }

}
public final class ValueFieldNamingStrategyTest {

    @org.junit.jupiter.api.Test
    public void test()
            throws IOException {
        final ConfigurableEnvironment configurableEnvironment = new StandardEnvironment();
        final MutablePropertySources propertySources = configurableEnvironment.getPropertySources();
        final PropertySource<?> propertySource = new MapPropertySource("test", ImmutableMap.of(
                "name", "FName",
                "data", "LName"
        ));
        propertySources.addLast(propertySource);
        final FieldNamingStrategy unit = ValueFieldNamingStrategy.of(configurableEnvironment);
        final Gson gson = new GsonBuilder()
                .disableHtmlEscaping()
                .disableInnerClassSerialization()
                .setFieldNamingStrategy(unit)
                .create();
        try ( final JsonReader jsonReader = /*...open JSON reader here...*/ ) {
            final Test test = gson.fromJson(jsonReader, Test.class);
            Assertions.assertEquals("FName", test.name);
            Assertions.assertEquals("LName", test.data);
        }
    }

    private static final class Test {

        @Value("${name}")
        private String name;

        @Value("${data}")
        private String data;

    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    相关资源
    最近更新 更多