【发布时间】:2012-09-22 18:58:12
【问题描述】:
Jackson 1.9.9 在解析成标量值(bool、int、string)时有些不一致。任何数组或对象类型都会失败,但您可以将任何标量类型放入字符串中。对于 bool 0 而不是 0 映射到 false/true。 int 属性只接受数字。
public class Foo { public String s; public boolean b; public int i; }
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.readValue("{\"s\":\"abc\"}", Foo.class).s); // "abc"
System.out.println(mapper.readValue("{\"s\":true}", Foo.class).s); // "true"
System.out.println(mapper.readValue("{\"s\":123}", Foo.class).s); // "123"
System.out.println(mapper.readValue("{\"b\":123}", Foo.class).b); // true
System.out.println(mapper.readValue("{\"b\":0}", Foo.class).b); // false
System.out.println(mapper.readValue("{\"b\":\"abc\"}", Foo.class).b); // fails with JsonMappingException
System.out.println(mapper.readValue("{\"i\":\"abc\"}", Foo.class).i); // fails with JsonMappingException
System.out.println(mapper.readValue("{\"i\":true}", Foo.class).i); // fails with JsonMappingException
System.out.println(mapper.readValue("{\"s\":[]}", Foo.class).s); // fails with JsonMappingException
System.out.println(mapper.readValue("{\"s\":{}}", Foo.class).s); // fails with JsonMappingException
System.out.println(mapper.readValue("{\"b\":[]}", Foo.class).b); // fails with JsonMappingException
System.out.println(mapper.readValue("{\"b\":{}}", Foo.class).b); // fails with JsonMappingException
System.out.println(mapper.readValue("{\"i\":[]}", Foo.class).i); // fails with JsonMappingException
System.out.println(mapper.readValue("{\"i\":{}}", Foo.class).i); // fails with JsonMappingException
Jackson 是否有 严格模式,如果有人将布尔值传递给 String 属性,我会收到错误消息?
我在一个 JAX-RS 项目中使用它,这使得基于 Jackson 抛出的异常的错误报告有些困难,因为我得到了大部分错误,但不是全部。我想避免获取原始 ObjectNode 并手动检查所有内容。如果调用者为字符串传递布尔值,那么我想告诉他,因为这很可能是编程错误。
【问题讨论】: