Prostitutor
Prostitutor

Reputation: 169

How to read Map of lists from Yaml file using Java

I have such Yaml file:

accept: 
- "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
accept-encoding: 
- "gzip, deflate"
accept-language: 
- "en-GB,en-US;q=0.9,en;q=0.8"
- "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,lt;q=0.6"
connection: 
- close
- keep-alive
dnt: 
- 1
referer: 
- "https://www.google.com/"
- "https://www.yahoo.com"
- "https://www.bing.com/"
upgrade-insecure-requests: 
- 1
- 0
x-real-ip: ~

And I try to read this with :

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
Map user = mapper.readValue(new File("/home/a/headers.yaml"), Map.class);
System.out.println(ReflectionToStringBuilder.toString(user, ToStringStyle.MULTI_LINE_STYLE));

but only can get single level of nesting. this I believe should be map of lists...

Upvotes: 2

Views: 4234

Answers (1)

Bentaye
Bentaye

Reputation: 9766

When I run your code it outputs:

java.util.LinkedHashMap@6500df86[
  accessOrder=false
  threshold=12
  loadFactor=0.75 
]

Which is the string representation of the Map object, not of what is inside.

The hard way:

If you want to use ReflectionToStringBuilder, I am afraid you will have to implement your own style by extending ToStringStyle. And your style would have to go through the Map and extract the keys and values.

The simple way:

However, you can achieve pretty much what you want with simple loops, and it is lot simpler, here is an example:

Map<String, List <Object>> user = 
    mapper.readValue(new File("/home/a/headers.yaml"), Map.class);

for(Map.Entry<String, List<Object>> entry : user.entrySet()) {
    System.out.println(entry.getKey());
    List<Object> values = entry.getValue();
    if(values != null) {
        for (Object value : values) {
            System.out.println("  - " + String.valueOf(value));
        }
    }
}

Given your file, it outputs:

accept
  - text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
accept-encoding
  - gzip, deflate
accept-language
  - en-GB,en-US;q=0.9,en;q=0.8
  - ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,lt;q=0.6
connection
  - close
  - keep-alive
dnt
  - 1
referer
  - https://www.google.com/
  - https://www.yahoo.com
  - https://www.bing.com/
upgrade-insecure-requests
  - 1
  - 0
x-real-ip

Upvotes: 1

Related Questions