我得到一个json:
{
"trackResponse": {
"shipment": [
{
"package": [
{
"trackingNumber": "Y0081040217",
"deliveryDate": [
{
"type": "DEL",
"date": "20200817"
}
],
"deliveryTime": {
"startTime": "",
"endTime": "145339",
"type": "DEL"
},
"activity": [
{
"location": {
"address": {
"city": "TORONTO",
"stateProvince": "",
"postalCode": "",
"country": "CA"
}
},
"status": {
"type": "D",
"description": "Delivered",
"code": "FS"
},
"date": "20200817",
"time": "145339"
},
我只想从此JSON保存几件事。例如 [trackingNumber,城市,国家,类型和描述] ,但我不知道应该从Java类中映射出哪种结构。
答案 0 :(得分:1)
由于您需要JSON
中的几个字段,因此建议您使用JSONPath API,以下是对maven的依赖。
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
下面是获取所需字段的代码
public static void main(String[] args) throws IOException {
String json = "{\r\n" +
" \"trackResponse\":{\r\n" +
" \"shipment\":[\r\n" +
" {\r\n" +
" \"package\":[\r\n" +
" {\r\n" +
" \"trackingNumber\":\"Y0081040217\",\r\n" +
" \"deliveryDate\":[\r\n" +
" {\r\n" +
" \"type\":\"DEL\",\r\n" +
" \"date\":\"20200817\"\r\n" +
" }\r\n" +
" ],\r\n" +
" \"deliveryTime\":{\r\n" +
" \"startTime\":\"\",\r\n" +
" \"endTime\":\"145339\",\r\n" +
" \"type\":\"DEL\"\r\n" +
" },\r\n" +
" \"activity\":[\r\n" +
" {\r\n" +
" \"location\":{\r\n" +
" \"address\":{\r\n" +
" \"city\":\"TORONTO\",\r\n" +
" \"stateProvince\":\"\",\r\n" +
" \"postalCode\":\"\",\r\n" +
" \"country\":\"CA\"\r\n" +
" }\r\n" +
" },\r\n" +
" \"status\":{\r\n" +
" \"type\":\"D\",\r\n" +
" \"description\":\"Delivered\",\r\n" +
" \"code\":\"FS\"\r\n" +
" },\r\n" +
" \"date\":\"20200817\",\r\n" +
" \"time\":\"145339\"\r\n" +
" }\r\n" +
" ]\r\n" +
" }\r\n" +
" ]\r\n" +
" }\r\n" +
" ]\r\n" +
" }\r\n" +
"}";
String[] jsonPaths = new String[5];
jsonPaths[0] = "$.trackResponse.shipment[*].package[*].trackingNumber";
jsonPaths[1] = "$.trackResponse.shipment[*].package[*].activity[*].location.address.city";
jsonPaths[2] = "$.trackResponse.shipment[*].package[*].activity[*].location.address.country";
jsonPaths[3] = "$.trackResponse.shipment[*].package[*].activity[*].status.description";
jsonPaths[4]= "$.trackResponse.shipment[*].package[*].activity[*].status.type";
DocumentContext jsonContext = JsonPath.parse(json);
for (String path : jsonPaths) {
List<String> result = jsonContext.read(path);
System.out.println(result.get(0)); //assuming there is only one array else u can iterate
}
}
结果
Y0081040217
TORONTO
CA
Delivered
D