jackson库是一款json解析的java库,其api比较多,而且容易混淆,今天我们就来看一下asText和textValue的区别。
假设有一个json数据:
{
"a": 1,
"b": {
"b_1": "b1",
"b_2": "b2"
},
"c": "2"
}
写一段代码对上面的json数据进行测试:
private static void test2() throws JsonMappingException, JsonProcessingException {
JsonNode readTree = mapper.readTree(json);
System.out.println("-----get a(int)-----");
JsonNode jsonNodea = readTree.get("a");
System.out.println("asInt:"+jsonNodea.asInt());
System.out.println("intValue:"+jsonNodea.intValue());
System.out.println("asText:"+jsonNodea.asText());
System.out.println("textValue:"+jsonNodea.textValue());
System.out.println("toPrettyString:"+jsonNodea.toPrettyString());
System.out.println("-----get c(string)-----");
JsonNode jsonNodec = readTree.get("c");
System.out.println("asText:"+jsonNodec.asText());
System.out.println("textValue:"+jsonNodec.textValue());
System.out.println("asInt:"+jsonNodec.asInt());
System.out.println("intValue:"+jsonNodec.intValue());
System.out.println("toPrettyString:"+jsonNodec.toPrettyString());
System.out.println("-----get b(object)-----");
JsonNode jsonNodeb = readTree.get("b");
System.out.println("asText:"+jsonNodeb.asText());
System.out.println("textValue:"+jsonNodeb.textValue());
System.out.println("asInt:"+jsonNodeb.asInt());
System.out.println("intValue:"+jsonNodeb.intValue());
System.out.println("toPrettyString:"+jsonNodeb.toPrettyString());
System.out.println("-----get d(not node)-----");
JsonNode jsonNoded = readTree.get("d");
System.out.println(jsonNoded.toPrettyString());
}
输出:
-----get a(int)-----
asInt:1
intValue:1
asText:1
textValue:null
toPrettyString:1
-----get c(string)-----
asText:2
textValue:2
asInt:2
intValue:0
toPrettyString:"2"
-----get b(object)-----
asText:
textValue:null
asInt:0
intValue:0
toPrettyString:{
"b_1" : "b1",
"b_2" : "b2"
}
-----get d-----
Exception in thread "main" java.lang.NullPointerException
at com.iqiyi.toutiao.Test.JacksonTest.test2(JacksonTest.java:98)
at com.iqiyi.toutiao.Test.JacksonTest.main(JacksonTest.java:102)
结论:
1、jackson通过get("字段名")api方法获取JsonNode对象时,如果该字段不存在,返回null;
2、如果json数据的某个字段值是基本类型(非object、array),可以使用jackson提供的asText、textValue,asInt、intValue...等方法来获取字段的值;如果字段值是复杂类型,那么上述方法将失效,可以使用toString()、toPrettyString()方法打印值。
3、对于字段值是基本类型的数据,如果是String类型,用 asText() 和 textValue() 获取的结果是一致的;同理,如果是int类型,用asInt()、intValue()获取的结果也是一致的;
4、asText()和textValue()方法都是获取字段是String基本类型的数据,区别是:
- asText()会进行强转,如果字段值不是string基本类型数据,会将其转成String基本类型的数据;(如果是复杂类型,返回空字符串)
- textValue()只针对String基本类型数据,所以如果字段值是非String基本类型数据,则返回null;
同理,asInt()和intValue()方法也是一样的:
- asInt()会进行强转,比如字符串类型的数字转成数字,如果强转失败(比如字符串abc),返回0;(如果是复杂类型,返回0)
- intValue()只针对int节本类型数据,对于非int基本类型数据,intValue返回0;