Java测试开发--JSONPath、JSONArray、JSONObject使用(十)
一、Maven项目,pom.xml文件中导入
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.75</version> </dependency>
二、JSONPath 使用时,注意绝对路径和相对路径,实例如下
{ "store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99,
"isbn": "0-553-21311-3"
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
上面一段json数据,获取价格字段的值
String jsonStr = "...."
绝对路径
List<Double> prices = (List<Double>) JSONPath.read(jsonStr, "$.store.book.price");
相对路径
List<String> names = (List<String>) JSONPath.read(jsonStr, "..price");
三、JSON转map
String json="{\"msg\":\"登录成功\",\"uid\":\"9CC972DFA2D4481F89841A46FD1B3E7B\",\"code\":\"1\"}";
Map map = JSON.parseObject(json,Map.class);
System.out.println("map==="+map.get("uid"));