Yaml数据示例:
--- !ruby/hash:ActionController::Parameters
title: "测试这是一句文本文案,看看你的问题是否已经解决了呢?"
options:
- !ruby/hash:ActionController::Parameters
option_name: "已经解决了"
option_select: 'false'
- !ruby/hash:ActionController::Parameters
option_name: "还没解决呢"
option_select: 'true'
Yaml解析工具类:
import org.yaml.snakeyaml.Yaml;
import java.util.Map;
/**
* @author P.H
* @date 2019/12/25 10:25
* @description Yaml解析
*/
public class YamlUtil {
public static MapparseYaml2Map(String str){
Yaml yaml = new Yaml();
return (Map)yaml.load(cleanYaml(str));
}
private static String cleanYaml(String yamlText) {
String tmpText = yamlText.replaceAll("^---.*\n", "---\n");
tmpText = tmpText.replaceAll("!ruby.*\n", "\n");
return tmpText;
}
/**
* ignore
*/
private static boolean ignore(String yamlText) {
if (yamlText == null) {
return false;
}
return yamlText.matches("---.*\\{}\n") || yamlText.matches("---.*\\[]\n") || yamlText.matches("-.*\\{}\n") || yamlText.matches("-.*\\[]\n");
}
}
实战解析:
import java.io.IOException;
/**
* @author PH
* @date 2019/12/24 19:20
* @description
*/
public class TestYaml {
public static void main(String[] args) throws IOException {
String str = "--- !ruby/hash:ActionController::Parameters\n" +
"title: \"测试这是一句文本文案,看看你的问题是否已经解决了呢?\"\n" +
"options:\n" +
"- !ruby/hash:ActionController::Parameters\n" +
" option_name: \"已经解决了\"\n" +
" option_select: 'false'\n" +
"- !ruby/hash:ActionController::Parameters\n" +
" option_name: \"还没解决呢\"\n" +
" option_select: 'true'\n";
System.out.println(YamlUtil.parseYaml2Map(str));
}
}
解析结果:
{title=测试这是一句文本文案,看看你的问题是否已经解决了呢?, options=[{option_name=已经解决了, option_select=false}, {option_name=还没解决呢, option_select=true}]}