正文
关于Jackson中JsonNode的取值asText()和textValue()区别
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
在 比较高版本的Jackson 中, 包名为 com.fasterxml.jackson
String jsonText="{\"name\":\"张三\","age":16,\"other\":\"312312.22\"}"
// JsonTools.text2Node() 为自己工具类请无视
JsonNode node = JsonTools.text2Node(jsonText);
// 一般我们需要从node中取值
node.get("name");
node.get("name").asText();
node.get("name").asText("默认值");
node.get("name").textValue(); // 结果依次是
// "张三"
// 张三
// 张三
// 张三 node.get("age").asText(); // 结果为: 16
node.get("age").textValue(); // 结果为: null // 关于asText()和textValue()的区别
上面很清楚的可以看到:
- 如果 字段本身的值为 text 类型 的, 那么用 asText() 和 textValue() 获取的结果是一致的;
- 如果 字段本身的值不是 text 类型的, 比如上面的 age 应该是数字类型的, 那么 asText() 会将最后的结果 转换为text 然后返回, 而 textValue() 则取不到值会返回空null, 此时需要用 intValue() /longValue()/数值类型的取值方法才能取到值;
- 同理 如果字段本身不是 int 整数型, 那么asInt() 会将获取的结果尝试转化为 int 然后返回, 而 intValue() 会返回空null;
4. 关于其他类型的获取值,同理: 如 longValue() 和 asLong() , asDouble() 和doubleValue();
需要补充一点, 如果字段在node中不存在, 则会报错空指针, 因为 他会是先获取,然后将结果转换为text 但是 在前面一步 get("")的结果已经为空;
差异在于, 没有值的 字段, 起码key 是有的,此时会处理value