我有这样的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));
但只能获得单一级别的嵌套。我相信这应该是列表的地图......
答案 0 :(得分: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