通过 YML 文件将地图中的符号和特殊字符作为键

Den*_*din 2 java spring key hashmap special-characters

是否可以存储通过 application.yml 映射的: ; / , .Java 中的映射键等字符?

我试图通过 application.yml 文件中的映射来存储 URI 以及与它们关联的值,但是由于它是一个键,因此它不会保存任何特殊字符

http://localhost:8080变为 httplocalhost8080

有什么办法可以保存那些丢失的字符吗?

~~编辑~~ 我已经尝试过在键周围使用转义字符、双引号和单引号,但一旦它们位于哈希图中,它们就会被忽略。

yml 文件中的属性具有以下结构:

  uri-example-config:
    keyToValueMap:
      http://localhost:8080 : String1
      http://exmaple.com: String2
      http://moreURIs.com: String2
Run Code Online (Sandbox Code Playgroud)

然后我的配置是:

@Configuration
@ConfigurationProperties(prefix = "uri-example-config")
@EnableConfigurationProperties
@Getter
@Setter
public class URIProperties {
    private Map<String, String> keyToValueMap = new HashMap<>();
}
Run Code Online (Sandbox Code Playgroud)

~~~~编辑2~~~~

是的,我可以轻松地使用 map.put(" http://localhost:8080 "...) 并且字符串按预期保留。通过带有配置和属性的 yml 文件执行此操作会导致此问题。

Erw*_*iel 5

Java HashMap 接受任何对象(字符串是对象)作为键! 另外,HashMap 不会写入/更改您的字符串。

我认为你的问题来自 .yml 的加载

如果使用双引号,Yaml 接受特殊字符作为键。

- "http://localhost:8080"
Run Code Online (Sandbox Code Playgroud)

检查您的串行器/解串器

编辑 有一个解释项目的github

您应该用括号将字符串括起来

- '[http://localhost:8080]'
Run Code Online (Sandbox Code Playgroud)