使用Java解析JSON数据并提取特定字段的实现步骤(以提取mailNo为例)
作者:码农阿豪@新空间代码工作室
1. 背景介绍
1.1 JSON简介
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。它基于JavaScript的一个子集,但独立于语言,几乎所有的编程语言都支持JSON格式的数据处理。
1.2 实际案例
假设我们有一个JSON数据,其中包含多个订单信息,每个订单都有一个唯一的mailNo字段。我们的目标是从这个JSON数据中提取出所有的mailNo字段,并将其存储在一个列表中。
2. 准备工作
2.1 环境搭建
为了解析JSON数据,我们需要使用一个Java库。在本文中,我们将使用Jackson库,这是一个非常流行的JSON处理库,功能强大且易于使用。
2.1.1 添加依赖
如果你使用Maven构建项目,可以在pom.xml中添加以下依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version>
</dependency>
如果你使用Gradle构建项目,可以在build.gradle中添加以下依赖:
implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.3'
2.2 JSON数据结构
以下是我们将要处理的JSON数据的示例:
{
"msg": "操作成功!",
"code": "ok",
"result": {
"records": [
{
"merchantId": 0,
"organId": 0,
"creatorId": 0,
"creatorTruename": "",
"creatorUsername": "",
"organName": "",
"merchantTruename": "",
"merchantUsername": "",
"consigneeName": "突然的自我",
"consigneePhone": "153****7763",
"consigneeTelPhone": "*******7763",
"consigneeCompany": "",
"consigneeProvinceId": 0,
"consigneeProvince": "四川省",
"consigneeCityId": 0,
"consigneeCity": "绵阳市",
"consigneeDistrictId": 0,
"consigneeDistrict": "涪城区",
"consigneeAddress": "四川省****靓妍美妆",
"sendProvinceId": 0,
"sendProvince": "贵州省",
"sendCityId": 0,
"sendCity": "遵义市",
"sendDistrictId": 0,
"sendDistrict": "红花岗区",
"senderName": "夜郎酒业",
"senderCompany": "",
"senderPhone": "155****7773",
"senderTelPhone": "*******7773",
"senderDetailAddress": "贵州省****中转仓库",
"mailNo": "SF3150804745040",
"subWaybillNoList": [],
"waybillStatus": 50,
"printSerialNumber": "",
"printStatus": 0,
"printNumber": 0,
"orderValueAddedVo": null,
"addedServiceCodes": [],
"callFlag": "",
"consignment": "夜郎酱宏图纯粮食大曲坤沙酒酱香型白酒礼盒装53度500ml",
"consignmentNumber": 2,
"parcelWeight": "2.0",
"parcelWeightUnit": "2.0",
"parcelQuantity": 1,
"meterageWeightQty": "2.0",
"realWeightQty": "2.0",
"orderNo": "6938567762089547327|2kBWWcmNUwX2SZ",
"originalOrderNo": "",
"signBackNo": "",
"remark": "",
"orderCreateTime": "2025-01-10 15:29:41",
"waybillCreateTime": "2025-01-10 15:29:41",
"printTime": null,
"isShowExcludeFile": 0,
"freight": "1000.0",
"referenceCost": "",
"waybillNums": 1,
"status": "",
"exceptionFlag": 0,
"promiseTime": "",
"receiveTime": "2025-01-10 16:16:55",
"signTime": "2025-01-11 14:13:40",
"latestRouteInfo": "您的快件已由本人签收,如有疑问请电联快递员【杨发斌,电话:13330891935】。您的体验对于我们至关重要,如果您对我们的服务有任何的想法和建议,请随时联系我们,我们一定用心倾听,全力改进,不辜负您的信任与支持。",
"latestOpCode": "80",
"expressProductId": 0,
"expressProductCode": "B1",
"expressProductName": "电商标快",
"expressPayMethod": 1,
"expressPayMethodName": "寄付月结",
"monthlyCard": "052***6969",
"orderType": 1,
"customField1": "",
"customField2": "",
"customField3": "",
"amount": "",
"collectionAmount": "",
"collectingNumber": "",
"oldCollectingMoney": "",
"exceptionCode": "",
"orderId": 0,
"waybillId": 0,
"isUpdateWaybill": 0,
"mergeOrderType": 2,
"isDraft": null,
"failCause": "",
"orderCrossBorderGoodsVoList": [
{
"productCode": "",
"productName": "夜郎酱宏图纯粮食大曲坤沙酒酱香型白酒礼盒装53度500ml",
"price": 0.0,
"currencyCode": "",
"currencyName": "",
"unit": "",
"productNumber": 2.0,
"orderType": 0,
"countryOfOrigin": ""
}
],
"gangAoTaiExtVo": null,
"swFlag": 0,
"sendStatus": 1,
"sendStatusName": "获取成功",
"expressCompanyMerchantId": 0,
"totalLength": 41.0,
"totalHeight": 1.0,
"totalWidth": 1.0,
"addedValueServiceInfo": {
"insuredType": 0,
"insuredPrice": null,
"collectingMoney": null,
"collectingMonthlyCard": "",
"signBackName": [],
"signBackNo": "",
"signBackWaybillStatus": 0,
"signBackOrderType": [],
"signBackRouteList": [],
"isSignBack": 0,
"signBackRemark": "",
"signBackNum": 0,
"thirdSignBack": 0,
"thirdConsigneeName": "",
"thirdConsigneePhone": "",
"thirdConsigneeTel": "",
"thirdConsigneeProvince": "",
"thirdConsigneeCity": "",
"thirdConsigneeArea": "",
"thirdConsigneeAddress": "",
"thirdConsigneeCompany": "",
"takePhotoBack": [],
"takePhotoNum": 0,
"takePhotoBackRemark": "",
"timingSendInformType": 0,
"timingSendInformDate": "",
"timingSendInformTime": "",
"electronicBack": 0,
"secretKeyAuthentication": "",
"secretKeyAuthenticationValue": "",
"woodenPackage": 0,
"woodenPackageInfo": "",
"readySend": 0,
"woodenRemovalNum": 0,
"packagingService": "",
"packagingMaterialVos": [],
"overweightService": 0,
"timingInsured": 0,
"freshService": 0,
"homeDeliveryExt": [],
"installationType": 0,
"installationContent": [],
"selfPickup": 0,
"exhibitionService": 0,
"exhibitionExitService": 0,
"addedServiceCodes": [],
"customDeliveryTime": ""
},
"signBackInfo": "",
"signBackNum": "",
"pickupAppointTime": "",
"consValueCurrencyCode": "",
"exportDeclarationMethod": "",
"customsBatchs": "",
"taxAccount": "",
"taxPaymentType": "",
"custReferenceNo": "",
"isSignBack": 0,
"signBackRemark": "",
"cancelTime": null
},
{
"merchantId": 0,
"organId": 0,
"creatorId": 0,
"creatorTruename": "",
"creatorUsername": "",
"organName": "",
"merchantTruename": "",
"merchantUsername": "",
"consigneeName": "**",
"consigneePhone": "157*********2541",
"consigneeTelPhone": "************2541",
"consigneeCompany": "",
"consigneeProvinceId": 0,
"consigneeProvince": "贵州省",
"consigneeCityId": 0,
"consigneeCity": "贵阳市",
"consigneeDistrictId": 0,
"consigneeDistrict": "修文县",
"consigneeAddress": "贵州省****兽霸鞋店",
"sendProvinceId": 0,
"sendProvince": "贵州省",
"sendCityId": 0,
"sendCity": "遵义市",
"sendDistrictId": 0,
"sendDistrict": "红花岗区",
"senderName": "小包",
"senderCompany": "",
"senderPhone": "155****1949",
"senderTelPhone": "*******1949",
"senderDetailAddress": "贵州省****菜鸟驿站",
"mailNo": "SF3150809345059",
"subWaybillNoList": [],
"waybillStatus": 50,
"printSerialNumber": "",
"printStatus": 0,
"printNumber": 0,
"orderValueAddedVo": null,
"addedServiceCodes": [],
"callFlag": "",
"consignment": "2024男鞋男士舒适时尚百搭黑色41",
"consignmentNumber": 1,
"parcelWeight": "2.5",
"parcelWeightUnit": "2.5",
"parcelQuantity": 1,
"meterageWeightQty": "2.5",
"realWeightQty": "2.5",
"orderNo": "6938535195456968508|6780cc24dd560100",
"originalOrderNo": "",
"signBackNo": "",
"remark": "驴孤品42码",
"orderCreateTime": "2025-01-10 15:28:59",
"waybillCreateTime": "2025-01-10 15:28:59",
"printTime": null,
"isShowExcludeFile": 0,
"freight": "1000.0",
"referenceCost": "",
"waybillNums": 1,
"status": "",
"exceptionFlag": 0,
"promiseTime": "",
"receiveTime": "2025-01-10 18:42:03",
"signTime": "2025-01-11 09:40:32",
"latestRouteInfo": "您的快件已由本人签收,如有疑问请电联快递员【王昭发,电话:18143512989】。您的体验对于我们至关重要,如果您对我们的服务有任何的想法和建议,请随时联系我们,我们一定用心倾听,全力改进,不辜负您的信任与支持。",
"latestOpCode": "80",
"expressProductId": 0,
"expressProductCode": "B1",
"expressProductName": "电商标快",
"expressPayMethod": 1,
"expressPayMethodName": "寄付月结",
"monthlyCard": "052***6969",
"orderType": 1,
"customField1": "",
"customField2": "",
"customField3": "",
"amount": "",
"collectionAmount": "",
"collectingNumber": "",
"oldCollectingMoney": "",
"exceptionCode": "",
"orderId": 0,
"waybillId": 0,
"isUpdateWaybill": 0,
"mergeOrderType": 2,
"isDraft": null,
"failCause": "",
"orderCrossBorderGoodsVoList": [
{
"productCode": "",
"productName": "2024男鞋男士舒适时尚百搭黑色41",
"price": 0.0,
"currencyCode": "",
"currencyName": "",
"unit": "",
"productNumber": 1.0,
"orderType": 0,
"countryOfOrigin": ""
}
],
"gangAoTaiExtVo": null,
"swFlag": 0,
"sendStatus": 1,
"sendStatusName": "获取成功",
"expressCompanyMerchantId": 0,
"totalLength": 0.0,
"totalHeight": 0.0,
"totalWidth": 0.0,
"addedValueServiceInfo": {
"insuredType": 0,
"insuredPrice": null,
"collectingMoney": null,
"collectingMonthlyCard": "",
"signBackName": [],
"signBackNo": "",
"signBackWaybillStatus": 0,
"signBackOrderType": [],
"signBackRouteList": [],
"isSignBack": 0,
"signBackRemark": "",
"signBackNum": 0,
"thirdSignBack": 0,
"thirdConsigneeName": "",
"thirdConsigneePhone": "",
"thirdConsigneeTel": "",
"thirdConsigneeProvince": "",
"thirdConsigneeCity": "",
"thirdConsigneeArea": "",
"thirdConsigneeAddress": "",
"thirdConsigneeCompany": "",
"takePhotoBack": [],
"takePhotoNum": 0,
"takePhotoBackRemark": "",
"timingSendInformType": 0,
"timingSendInformDate": "",
"timingSendInformTime": "",
"electronicBack": 0,
"secretKeyAuthentication": "",
"secretKeyAuthenticationValue": "",
"woodenPackage": 0,
"woodenPackageInfo": "",
"readySend": 0,
"woodenRemovalNum": 0,
"packagingService": "",
"packagingMaterialVos": [],
"overweightService": 0,
"timingInsured": 0,
"freshService": 0,
"homeDeliveryExt": [],
"installationType": 0,
"installationContent": [],
"selfPickup": 0,
"exhibitionService": 0,
"exhibitionExitService": 0,
"addedServiceCodes": [],
"customDeliveryTime": ""
},
"signBackInfo": "",
"signBackNum": "",
"pickupAppointTime": "",
"consValueCurrencyCode": "",
"exportDeclarationMethod": "",
"customsBatchs": "",
"taxAccount": "",
"taxPaymentType": "",
"custReferenceNo": "",
"isSignBack": 0,
"signBackRemark": "",
"cancelTime": null
}
],
"total": 5167,
"size": 1000,
"current": 1,
"orders": [],
"searchCount": true,
"pages": 6
}
}
3. 实现步骤
3.1 创建Java类
我们将创建一个名为MailNoExtractor的Java类,用于解析JSON数据并提取mailNo字段。
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MailNoExtractor {
public static List<String> extractMailNos(String json) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(json);
JsonNode recordsNode = rootNode.path("result").path("records");
List<String> mailNos = new ArrayList<>();
for (JsonNode record : recordsNode) {
String mailNo = record.path("mailNo").asText();
mailNos.add(mailNo);
}
return mailNos;
}
public static void main(String[] args) {
String json = "{\"msg\":\"操作成功!\",\"code\":\"ok\",\"result\":{\"records\":[{\"merchantId\":0,\"organId\":0,\"creatorId\":0,\"creatorTruename\":\"\",\"creatorUsername\":\"\",\"organName\":\"\",\"merchantTruename\":\"\",\"merchantUsername\":\"\",\"consigneeName\":\"突然的自我\",\"consigneePhone\":\"153****7763\",\"consigneeTelPhone\":\"*******7763\",\"consigneeCompany\":\"\",\"consigneeProvinceId\":0,\"consigneeProvince\":\"四川省\",\"consigneeCityId\":0,\"consigneeCity\":\"绵阳市\",\"consigneeDistrictId\":0,\"consigneeDistrict\":\"涪城区\",\"consigneeAddress\":\"四川省****靓妍美妆\",\"sendProvinceId\":0,\"sendProvince\":\"贵州省\",\"sendCityId\":0,\"sendCity\":\"遵义市\",\"sendDistrictId\":0,\"sendDistrict\":\"红花岗区\",\"senderName\":\"夜郎酒业\",\"senderCompany\":\"\",\"senderPhone\":\"155****7773\",\"senderTelPhone\":\"*******7773\",\"senderDetailAddress\":\"贵州省****中转仓库\",\"mailNo\":\"SF3150804745040\",\"subWaybillNoList\":[],\"waybillStatus\":50,\"printSerialNumber\":\"\",\"printStatus\":0,\"printNumber\":0,\"orderValueAddedVo\":null,\"addedServiceCodes\":[],\"callFlag\":\"\",\"consignment\":\"夜郎酱宏图纯粮食大曲坤沙酒酱香型白酒礼盒装53度500ml\",\"consignmentNumber\":2,\"parcelWeight\":\"2.0\",\"parcelWeightUnit\":\"2.0\",\"parcelQuantity\":1,\"meterageWeightQty\":\"2.0\",\"realWeightQty\":\"2.0\",\"orderNo\":\"6938567762089547327|2kBWWcmNUwX2SZ\",\"originalOrderNo\":\"\",\"signBackNo\":\"\",\"remark\":\"\",\"orderCreateTime\":\"2025-01-10 15:29:41\",\"waybillCreateTime\":\"2025-01-10 15:29:41\",\"printTime\":null,\"isShowExcludeFile\":0,\"freight\":\"1000.0\",\"referenceCost\":\"\",\"waybillNums\":1,\"status\":\"\",\"exceptionFlag\":0,\"promiseTime\":\"\",\"receiveTime\":\"2025-01-10 16:16:55\",\"signTime\":\"2025-01-11 14:13:40\",\"latestRouteInfo\":\"您的快件已由本人签收,如有疑问请电联快递员【杨发斌,电话:13330891935】。您的体验对于我们至关重要,如果您对我们的服务有任何的想法和建议,请随时联系我们,我们一定用心倾听,全力改进,不辜负您的信任与支持。\",\"latestOpCode\":\"80\",\"expressProductId\":0,\"expressProductCode\":\"B1\",\"expressProductName\":\"电商标快\",\"expressPayMethod\":1,\"expressPayMethodName\":\"寄付月结\",\"monthlyCard\":\"052***6969\",\"orderType\":1,\"customField1\":\"\",\"customField2\":\"\",\"customField3\":\"\",\"amount\":\"\",\"collectionAmount\":\"\",\"collectingNumber\":\"\",\"oldCollectingMoney\":\"\",\"exceptionCode\":\"\",\"orderId\":0,\"waybillId\":0,\"isUpdateWaybill\":0,\"mergeOrderType\":2,\"isDraft\":null,\"failCause\":\"\",\"orderCrossBorderGoodsVoList\":[{\"productCode\":\"\",\"productName\":\"夜郎酱宏图纯粮食大曲坤沙酒酱香型白酒礼盒装53度500ml\",\"price\":0.0,\"currencyCode\":\"\",\"currencyName\":\"\",\"unit\":\"\",\"productNumber\":2.0,\"orderType\":0,\"countryOfOrigin\":\"\"}],\"gangAoTaiExtVo\":null,\"swFlag\":0,\"sendStatus\":1,\"sendStatusName\":\"获取成功\",\"expressCompanyMerchantId\":0,\"totalLength\":41.0,\"totalHeight\":1.0,\"totalWidth\":1.0,\"addedValueServiceInfo\":{\"insuredType\":0,\"insuredPrice\":null,\"collectingMoney\":null,\"collectingMonthlyCard\":\"\",\"signBackName\":[],\"signBackNo\":\"\",\"signBackWaybillStatus\":0,\"signBackOrderType\":[],\"signBackRouteList\":[],\"isSignBack\":0,\"signBackRemark\":\"\",\"signBackNum\":0,\"thirdSignBack\":0,\"thirdConsigneeName\":\"\",\"thirdConsigneePhone\":\"\",\"thirdConsigneeTel\":\"\",\"thirdConsigneeProvince\":\"\",\"thirdConsigneeCity\":\"\",\"thirdConsigneeArea\":\"\",\"thirdConsigneeAddress\":\"\",\"thirdConsigneeCompany\":\"\",\"takePhotoBack\":[],\"takePhotoNum\":0,\"takePhotoBackRemark\":\"\",\"timingSendInformType\":0,\"timingSendInformDate\":\"\",\"timingSendInformTime\":\"\",\"electronicBack\":0,\"secretKeyAuthentication\":\"\",\"secretKeyAuthenticationValue\":\"\",\"woodenPackage\":0,\"woodenPackageInfo\":\"\",\"readySend\":0,\"woodenRemovalNum\":0,\"packagingService\":\"\",\"packagingMaterialVos\":[],\"overweightService\":0,\"timingInsured\":0,\"freshService\":0,\"homeDeliveryExt\":[],\"installationType\":0,\"installationContent\":[],\"selfPickup\":0,\"exhibitionService\":0,\"exhibitionExitService\":0,\"addedServiceCodes\":[],\"customDeliveryTime\":\"\"},\"signBackInfo\":\"\",\"signBackNum\":\"\",\"pickupAppointTime\":\"\",\"consValueCurrencyCode\":\"\",\"exportDeclarationMethod\":\"\",\"customsBatchs\":\"\",\"taxAccount\":\"\",\"taxPaymentType\":\"\",\"custReferenceNo\":\"\",\"isSignBack\":0,\"signBackRemark\":\"\",\"cancelTime\":null},{\"merchantId\":0,\"organId\":0,\"creatorId\":0,\"creatorTruename\":\"\",\"creatorUsername\":\"\",\"organName\":\"\",\"merchantTruename\":\"\",\"merchantUsername\":\"\",\"consigneeName\":\"**\",\"consigneePhone\":\"157*********2541\",\"consigneeTelPhone\":\"************2541\",\"consigneeCompany\":\"\",\"consigneeProvinceId\":0,\"consigneeProvince\":\"贵州省\",\"consigneeCityId\":0,\"consigneeCity\":\"贵阳市\",\"consigneeDistrictId\":0,\"consigneeDistrict\":\"修文县\",\"consigneeAddress\":\"贵州省****兽霸鞋店\",\"sendProvinceId\":0,\"sendProvince\":\"贵州省\",\"sendCityId\":0,\"sendCity\":\"遵义市\",\"sendDistrictId\":0,\"sendDistrict\":\"红花岗区\",\"senderName\":\"小包\",\"senderCompany\":\"\",\"senderPhone\":\"155****1949\",\"senderTelPhone\":\"*******1949\",\"senderDetailAddress\":\"贵州省****菜鸟驿站\",\"mailNo\":\"SF3150809345059\",\"subWaybillNoList\":[],\"waybillStatus\":50,\"printSerialNumber\":\"\",\"printStatus\":0,\"printNumber\":0,\"orderValueAddedVo\":null,\"addedServiceCodes\":[],\"callFlag\":\"\",\"consignment\":\"2024男鞋男士舒适时尚百搭黑色41\",\"consignmentNumber\":1,\"parcelWeight\":\"2.5\",\"parcelWeightUnit\":\"2.5\",\"parcelQuantity\":1,\"meterageWeightQty\":\"2.5\",\"realWeightQty\":\"2.5\",\"orderNo\":\"6938535195456968508|6780cc24dd560100\",\"originalOrderNo\":\"\",\"signBackNo\":\"\",\"remark\":\"驴孤品42码\",\"orderCreateTime\":\"2025-01-10 15:28:59\",\"waybillCreateTime\":\"2025-01-10 15:28:59\",\"printTime\":null,\"isShowExcludeFile\":0,\"freight\":\"1000.0\",\"referenceCost\":\"\",\"waybillNums\":1,\"status\":\"\",\"exceptionFlag\":0,\"promiseTime\":\"\",\"receiveTime\":\"2025-01-10 18:42:03\",\"signTime\":\"2025-01-11 09:40:32\",\"latestRouteInfo\":\"您的快件已由本人签收,如有疑问请电联快递员【王昭发,电话:18143512989】。您的体验对于我们至关重要,如果您对我们的服务有任何的想法和建议,请随时联系我们,我们一定用心倾听,全力改进,不辜负您的信任与支持。\",\"latestOpCode\":\"80\",\"expressProductId\":0,\"expressProductCode\":\"B1\",\"expressProductName\":\"电商标快\",\"expressPayMethod\":1,\"expressPayMethodName\":\"寄付月结\",\"monthlyCard\":\"052***6969\",\"orderType\":1,\"customField1\":\"\",\"customField2\":\"\",\"customField3\":\"\",\"amount\":\"\",\"collectionAmount\":\"\",\"collectingNumber\":\"\",\"oldCollectingMoney\":\"\",\"exceptionCode\":\"\",\"orderId\":0,\"waybillId\":0,\"isUpdateWaybill\":0,\"mergeOrderType\":2,\"isDraft\":null,\"failCause\":\"\",\"orderCrossBorderGoodsVoList\":[{\"productCode\":\"\",\"productName\":\"2024男鞋男士舒适时尚百搭黑色41\",\"price\":0.0,\"currencyCode\":\"\",\"currencyName\":\"\",\"unit\":\"\",\"productNumber\":1.0,\"orderType\":0,\"countryOfOrigin\":\"\"}],\"gangAoTaiExtVo\":null,\"swFlag\":0,\"sendStatus\":1,\"sendStatusName\":\"获取成功\",\"expressCompanyMerchantId\":0,\"totalLength\":0.0,\"totalHeight\":0.0,\"totalWidth\":0.0,\"addedValueServiceInfo\":{\"insuredType\":0,\"insuredPrice\":null,\"collectingMoney\":null,\"collectingMonthlyCard\":\"\",\"signBackName\":[],\"signBackNo\":\"\",\"signBackWaybillStatus\":0,\"signBackOrderType\":[],\"signBackRouteList\":[],\"isSignBack\":0,\"signBackRemark\":\"\",\"signBackNum\":0,\"thirdSignBack\":0,\"thirdConsigneeName\":\"\",\"thirdConsigneePhone\":\"\",\"thirdConsigneeTel\":\"\",\"thirdConsigneeProvince\":\"\",\"thirdConsigneeCity\":\"\",\"thirdConsigneeArea\":\"\",\"thirdConsigneeAddress\":\"\",\"thirdConsigneeCompany\":\"\",\"takePhotoBack\":[],\"takePhotoNum\":0,\"takePhotoBackRemark\":\"\",\"timingSendInformType\":0,\"timingSendInformDate\":\"\",\"timingSendInformTime\":\"\",\"electronicBack\":0,\"secretKeyAuthentication\":\"\",\"secretKeyAuthenticationValue\":\"\",\"woodenPackage\":0,\"woodenPackageInfo\":\"\",\"readySend\":0,\"woodenRemovalNum\":0,\"packagingService\":\"\",\"packagingMaterialVos\":[],\"overweightService\":0,\"timingInsured\":0,\"freshService\":0,\"homeDeliveryExt\":[],\"installationType\":0,\"installationContent\":[],\"selfPickup\":0,\"exhibitionService\":0,\"exhibitionExitService\":0,\"addedServiceCodes\":[],\"customDeliveryTime\":\"\"},\"signBackInfo\":\"\",\"signBackNum\":\"\",\"pickupAppointTime\":\"\",\"consValueCurrencyCode\":\"\",\"exportDeclarationMethod\":\"\",\"customsBatchs\":\"\",\"taxAccount\":\"\",\"taxPaymentType\":\"\",\"custReferenceNo\":\"\",\"isSignBack\":0,\"signBackRemark\":\"\",\"cancelTime\":null}],\"total\":5167,\"size\":1000,\"current\":1,\"orders\":[],\"searchCount\":true,\"pages\":6}}";
try {
List<String> mailNos = extractMailNos(json);
for (String mailNo : mailNos) {
System.out.println(mailNo);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.2 代码解析
3.2.1 extractMailNos 方法
- 功能:该方法接收一个JSON字符串作为输入,使用Jackson库解析JSON,并提取出所有
mailNo字段的值,返回一个包含所有mailNo的列表。 - 步骤:
- 使用
ObjectMapper将JSON字符串解析为JsonNode对象。 - 通过
path方法获取result节点下的records数组。 - 遍历
records数组,提取每个记录中的mailNo字段,并将其添加到列表中。
- 使用
3.2.2 main 方法
- 功能:这是一个简单的测试方法,展示了如何使用
extractMailNos方法来提取mailNo并打印出来。 - 步骤:
- 定义一个JSON字符串。
- 调用
extractMailNos方法提取mailNo。 - 遍历并打印所有
mailNo。
3.3 运行结果
运行上述代码后,输出结果如下:
SF3150804745040
SF3150809345059
4. 总结
本文详细介绍了如何使用Java解析JSON数据并提取特定字段。通过使用Jackson库,我们可以轻松地处理复杂的JSON数据结构,并提取出我们需要的字段。这个工具类可以根据实际需求进一步扩展和优化,例如添加异常处理、支持更多字段的提取等。
希望本文对你理解和使用Java处理JSON数据有所帮助!
到此这篇关于使用Java解析JSON数据并提取特定字段的实现步骤(以提取mailNo为例)的文章就介绍到这了,更多相关Java解析JSON数据并提取字段内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
