jyaml解析float类型的问题
今天在使用jyaml解析一个配置类的时候,发现一个问题:
- 整型和字符串的解析都没有问题
- float类型的解析则总是返回
0.0F,无论是对值用引号包括,或者在后面加上大写的F,都是不行的。
写了个简单的测试用例:
import lombok.Data;
import org.ho.yaml.Yaml;
import org.junit.Assert;
import org.junit.Test;
public class TestYaml {
@Test
public void testLoadYaml() {
String yamlStr = "foo: 1.2\nnum: 2000\nbar: 0.4";
TestConf conf = Yaml.loadType(yamlStr, TestConf.class);
Assert.assertEquals(2000, conf.getNum());
Assert.assertEquals(1.2F, conf.getFoo(), 0.0F);
Assert.assertEquals(0.4F, conf.getBar(), 0.0F);
}
@Data
public static class TestConf
{
private int num;
private float foo;
private Float bar;
}
}测试总是通不过:
后面经同事提醒,把float换成double类型就可以了,不过,不能精确匹配,总是有偏差的。新的测试用例如下:
import lombok.Data;
import org.ho.yaml.Yaml;
import org.junit.Assert;
import org.junit.Test;
public class TestYaml {
@Test
public void testLoadYaml() {
String yamlStr = "foo: 1.2\nnum: 2000\nbar: 0.4";
TestConf conf = Yaml.loadType(yamlStr, TestConf.class);
Assert.assertEquals(2000, conf.getNum());
Assert.assertEquals(0.0F, conf.getFoo(), 0.0001F);
Assert.assertEquals(0.4F, conf.getBar(), 0.0001F);
}
@Data
public static class TestConf
{
private int num;
private float foo;
private Double bar;
}
}终于通过去了,鉴于时间有限,详细原因后续再深究。
今天又看了一下yaml官网上推荐的其他的类库。
Java:
- JvYaml # Java port of RbYaml
- SnakeYAML # Java 5 / YAML 1.1
- YamlBeans # To/from JavaBeans
- JYaml # Original Java Implementation
- Camel # YAML 1.2 for Java. A user-friendly OOP library.
最后选择了snakeyaml下手。发现在这个库问题手到擒来,看来还是jyaml本身代码的问题。
要使用snakeyaml,在pom.xml中引入依赖即可
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.23</version>
</dependency>上一下snakeyaml的测试用例:
import lombok.Data;
import org.junit.Assert;
import org.junit.Test;
import org.yaml.snakeyaml.Yaml;
public class TestYaml {
@Test
public void testLoadYaml() {
String yamlStr = "foo: 1.2\nnum: 2000\nbar: 0.4";
Yaml yaml = new Yaml();
TestConf conf = yaml.loadAs(yamlStr, TestConf.class);
Assert.assertEquals(2000, conf.getNum());
Assert.assertEquals(1.2F, conf.getFoo(), 0.0001F);
Assert.assertEquals(0.4F, conf.getBar(), 0.0001F);
}
@Data
public static class TestConf
{
private int num;
private float foo;
private Double bar;
}
}