Java測試開發--JSONPath、JSONArray、JSONObject使用(十)
阿新 • • 發佈:2021-09-01
一、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"));