【发布时间】:2017-07-18 12:35:43
【问题描述】:
我需要在 yml 属性中使用 Map<String, Object>,但允许在映射中输入具有 null 值的键。
例如:
application.yml
....
init-services:
sample-service-discovery:
port: 8761
profiles: dev,prod
sample-config-server:
port: 8888
profiles: dev, test
sample-activation-service:
some-other-service:
port: 1234
....
init-services 是 Map<String, ServiceProperties>。
ServiceProperties 只是一个带有Integer port, List<String> profiles 的 POJO。
前 2 个条目编译得很好,但在 sample-activation-service 我得到 Cannot convert value of type 'java.lang.String' to required type PathProperties$ServiceProperties 异常。
问题:有没有办法允许在 .yml 映射中只有一个键但 null 值为 null 的条目?稍后我需要遍历这些键,即使它们的值为空。
【问题讨论】:
-
你可以有一个
nullYAML 的键,但这使它成为一个非字符串标量。你确定你想要“带有空值的字符串键”,这对我来说看起来像是一个矛盾。 -
我不想要一个空键,我想要一个键的空值。因此,如果在我的代码中:
map.get("sample-activation-service")它返回null。如果我的措辞不够清楚,我愿意接受建议/编辑。我编辑了这个问题,试图让它更清楚。如果有帮助,请告诉我。 -
抱歉,我不知道如何使用 Java 生成它。但
{null: 1, True: x, x: 42}是有效的 YAML。当然,任何映射中只能有一个null键,因为映射的键必须是唯一的。 -
正如我在之前的评论中所说,我正在寻找一个空值,而不是一个空键。我的 yaml 文件中的
sample-activation-service:是键,它应该有一个对象作为值,但我希望该值简单地为空或 null。目前,至少对于 Spring Boot,这是行不通的。如果我的问题上的 yaml 标签有误导性,我会删除它
标签: spring-boot yaml