第二章写了一种自己写的方法来查找json字符串中的值,其实jackson还提供一个find方法来查找json字符串中的值。今天我们一起来看看这个方法的使用……
按照惯例我先贴上代码
/**
* 具体的类我就不贴出来浪费空间了
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// 准备数据
List<Person> pers = new ArrayList<Person>();
List<Person> childs = new ArrayList<Person>();
Person p = new Person("张三", 46);
childs.add(new Person("小张三1", 20));
childs.add(new Person("小张三2", 17));
p.setChilds(childs);
pers.add(p);
p = new Person("李四", 29);
childs = new ArrayList<Person>();
childs.add(new Person("小李四1", 20));
p.setChilds(childs);
pers.add(p);
p = new Person("王二麻子", 23);
pers.add(p);
TestVo vo = new TestVo(null, pers);
ObjectMapper mapper = JsonProcessUtil.getMapperInstance(false);
String voJson = JsonProcessUtil.toJson(vo);
JsonNode node = mapper.readTree(voJson);
getValueByFind(node, "age");
getFirstValueByFind(node, "age");
}
哈哈,这样写是不是比第二篇里面的方便多了?但是有个缺点啊,不能指定路径。也就是说它会把当前json字符串中的所有匹配属性的值都取出来,如果你没有指定路径的要求 这种方法无疑很方便。
好了贴上两个方法的代码……
/**
* 使用find的方法从实体中取出所有匹配的值
*
* @param vo
* @param path
* @return
*/
public static List<String> getValueByFind(JsonNode node, String path) throws Exception {
List<String> values = new ArrayList<String>();
/*
* values = node.findValuesAsText(path); 这里提供两种方法 一种是只填写path
* 它会返回List<String>,另外一种就是下面用的 它会直接把找到的value填到你传入的集合中
*/
node.findValuesAsText(path, values);
System.out.println(Arrays.toString(values.toArray()));
return values;
}
/**
* 查找当前Node中第一个匹配的值
*
* @param node
* @param path
* @return
* @throws Exception
*/
public static int getFirstValueByFind(JsonNode node, String path) throws Exception {
/*
* 注意这点不能使用getTextValue()方法,因为找到的值为Int类型的所以使用getTextValue是查不到值的。
* 不过如果想返回String字符串可以使用asText()方法。这里使用asInt是为了看到其实JackSon是可以直接返回相应类型的值的。
*/
int value = node.findValue(path).asInt();
System.out.println(value);
return value;
}