Symbols and special characters in maps as keys THROUGH YML FILE

Viewed 6686

Is it possible to store characters such as : ; / , . in the keys in map in Java that's mapped through application.yml?

I'm trying to store URIs and a value associated with them through a mapping in application.yml file however since it's a key, it doesnt save any of the special characters

http://localhost:8080 becomes httplocalhost8080

Is there any way to preserve those lost characters?

~~EDIT~~ I've tried escape characters, double, and single quotes around the keys and still once they are in the hashmap, they are ignored.

The property in the yml file has this structure:

  uri-example-config:
    keyToValueMap:
      http://localhost:8080 : String1
      http://exmaple.com: String2
      http://moreURIs.com: String2

And then my config is:

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

~~~~EDIT 2~~~~

Yes, i can easily map.put("http://localhost:8080"...) and the strings is preserved as expected. Doing it through yml file with config and properties causes this issue.

4 Answers

Java HashMap accept any Object (String is an Object) as key ! Also, HashMap will not write/change your String.

I think your problem comes from the loading of your .yml

Yaml accept special characters as key if its in double quote.

- "http://localhost:8080"

Check your serializer / deserializer

Edit There is an explanation on the github of the project

You should surround your string with brackets

- '[http://localhost:8080]'

Maybe you can create an URI like this:

URI uri = new URI("http", null, "localhost", "8080", "/my/api");
String uriAsString = uri.toASCIIString();

And then set it into your map as a string.

I suggest you to look at this post, you might find a solution there: HTTP URL Address Encoding in Java

Yes it is

For your example in java you just have to escape it right.

    Map testmap=new HashMap<String,Object>();
    Object testObject="a value Object";
    testmap.put("http://localhost:8080",testObject);
    for (Object s:testmap.keySet()) {
        System.out.println(s);
    }

Will print out:

http://localhost:8080

Yes, it is possible to use characters like : ; / , . in a String key Map, if the key is of type String so the Map can accept any string with any character.

The key should be of type a class that implements equals and hashCode methods. If these methods aren't available so they will be inherited from the Object class.

Related