代码场景一
Yaml yaml = new Yaml();
String yamlStr = "value:\n"
+ " - {a: 'b', c: 86:00.0}\n";
LinkedHashMap<String, Object> map = yaml.loadAs(yamlStr, LinkedHashMap.class);
System.out.println( ((Map)((List)map.get("value")).get(0)).get("c") );
代码场景二(解析时间字符串)
Yaml yaml = new Yaml();
String yamlStr = "value:\n"
+ " - {a: 'b', c: 10:45:12}\n";
LinkedHashMap<String, Object> map = yaml.loadAs(yamlStr, LinkedHashMap.class);
System.out.println( ((Map)((List)map.get("value")).get(0)).get("c") );
代码场景一和代码场景二其实我们想要的结果都是字符串,但是解析出来后,是一个float类型,并且已经不是我们想要的value了,如代码场景一,”86:00.0“ 已经读取为了 “ 5160.0”。
这是因为snakeyaml预设了float的定义规则。
解决方法
1.继承类Resolver,注释掉float和int的定义,注释掉哪些就看自己的需求了哈,如下代码仅仅是参考。
public class MyResolver extends Resolver {
public static final Pattern BOOL = Pattern.compile("^(?:yes|Yes|YES|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF)$");
public static final Pattern FLOAT = Pattern.compile("^([-+]?(\\.[0-9]+|[0-9_]+(\\.[0-9_]*)?)([eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
public static final Pattern INT = Pattern.compile("^(?:[-+]?0b[0-1_]+|[-+]?0[0-7_]+|[-+]?(?:0|[1-9][0-9_]*)|[-+]?0x[0-9a-fA-F_]+|[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$");
public static final Pattern MERGE = Pattern.compile("^(?:<<)$");
public static final Pattern NULL = Pattern.compile("^(?:~|null|Null|NULL| )$");
public static final Pattern EMPTY = Pattern.compile("^$");
public static final Pattern TIMESTAMP = Pattern.compile("^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]|[0-9][0-9][0-9][0-9]-[0-9][0-9]?-[0-9][0-9]?(?:[Tt]|[ \t]+)[0-9][0-9]?:[0-9][0-9]:[0-9][0-9](?:\\.[0-9]*)?(?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$");
public static final Pattern VALUE = Pattern.compile("^(?:=)$");
public static final Pattern YAML = Pattern.compile("^(?:!|&|\\*)$");
@Override
protected void addImplicitResolvers() {
this.addImplicitResolver(Tag.BOOL, BOOL, "yYnNtTfFoO");
//this.addImplicitResolver(Tag.INT, INT, "-+0123456789");
//this.addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789.");
this.addImplicitResolver(Tag.MERGE, MERGE, "<");
this.addImplicitResolver(Tag.NULL, NULL, "~nN\u0000");
this.addImplicitResolver(Tag.NULL, EMPTY, (String)null);
this.addImplicitResolver(Tag.TIMESTAMP, TIMESTAMP, "0123456789");
this.addImplicitResolver(Tag.YAML, YAML, "!&*");
}
}
2.初始化Yaml实例
Yaml yaml = new Yaml( new Constructor(), new Representer(), new DumperOptions(), new LoaderOptions(),new MyResolver());
最后
当然,如果能和数据提供方沟通好数据格式的话,那样就没有这个问题了。比如在要被识别为字符串的值统一加一个单引号。