【问题标题】:How to read Map of lists from Yaml file using Java如何使用 Java 从 Yaml 文件中读取列表映射
【发布时间】:2018-05-16 15:39:21
【问题描述】:

我有这样的 Yaml 文件:

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: ~

我尝试阅读:

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));

但只能获得单层嵌套。我认为这应该是列表的地图...

【问题讨论】:

  • 请提供您的预期输出。用户 Map 为 {accept=[text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8],accept-编码=[gzip, deflate], 接受语言=[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=[google.com, yahoo.com, bing.com/], upgrade-insecure-requests=[ 1, 0], x-real-ip=null} 这似乎没问题

标签: java jackson yaml


【解决方案1】:

当我运行你的代码时,它会输出:

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

这是 Map 对象的字符串表示形式,而不是里面的内容。

艰难的道路:

如果你想使用ReflectionToStringBuilder,恐怕你将不得不通过扩展ToStringStyle来实现自己的风格。而且您的样式必须通过 Map 并提取键和值。

简单的方法:

不过,你可以通过简单的循环实现几乎你想要的,而且要简单得多,这里有一个例子:

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));
        }
    }
}

给定你的文件,它会输出:

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

【讨论】:

    猜你喜欢
    • 2019-10-17
    • 2011-02-27
    • 2011-12-30
    • 2019-07-30
    • 2020-11-09
    • 2018-11-23
    • 2023-03-03
    • 2021-02-08
    • 2019-06-18
    相关资源
    最近更新 更多