使用Java解析JSON数据并提取特定字段的实现步骤(以提取mailNo为例)

本文主要是介绍使用Java解析JSON数据并提取特定字段的实现步骤(以提取mailNo为例),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《使用Java解析JSON数据并提取特定字段的实现步骤(以提取mailNo为例)》在现代软件开发中,处理JSON数据是一项非常常见的任务,无论是从API接口获取数据,还是将数据存储为JSON格式,解析...

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": "",
 China编程       "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,
        "fjsailCause": "",
        "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.databihttp://www.chinasem.cnnd.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\":0android,\"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\":\"\",\China编程"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的列表。
  • 步骤
    1. 使用ObjectMapper将JSON字符串解析为JsonNode对象。
    2. 通过path方法获取result节点下的records数组。
    3. 遍历records数组,提取每个记录中的mailNo字段,并将其添加到列表中。

3.2.2 main 方法

  • 功能:这是一个简单的测试方法,展示了如何使用extractMailNos方法来提取mailNo并打印出来。
  • 步骤
    1. 定义一个JSON字符串。
    2. 调用extractMailNos方法提取mailNo
    3. 遍历并打印所有mailNo

3.3 运行结果

运行上述代码后,输出结果如下:

SF3150804745040
SF3150809345059

4. 总结

本文详细介绍了如何使用Java解析JSON数据并提取特定字段。通过使用Jackson库,我们可以轻松地处理复杂的JSON数据结构,并提取出我们需要的字段。这个工具类可以根据实际需求进一步扩展和优化,例如添加异常处理、支持更多字段的提取等。

希望本文对你理解和使用Java处理JSON数据有所帮助!

到此这篇关于使用Java解析JSON数据并提取特定字段的实现步骤(以提取mailNo为例)的文章就介绍到这了,更多相关Java解析JSON数据并提取字段内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持China编程(www.chinasem.cn)!

这篇关于使用Java解析JSON数据并提取特定字段的实现步骤(以提取mailNo为例)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1153045

相关文章

springboot健康检查监控全过程

《springboot健康检查监控全过程》文章介绍了SpringBoot如何使用Actuator和Micrometer进行健康检查和监控,通过配置和自定义健康指示器,开发者可以实时监控应用组件的状态,... 目录1. 引言重要性2. 配置Spring Boot ActuatorSpring Boot Act

MySQL中删除重复数据SQL的三种写法

《MySQL中删除重复数据SQL的三种写法》:本文主要介绍MySQL中删除重复数据SQL的三种写法,文中通过代码示例讲解的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下... 目录方法一:使用 left join + 子查询删除重复数据(推荐)方法二:创建临时表(需分多步执行,逻辑清晰,但会

Java实现任务管理器性能网络监控数据的方法详解

《Java实现任务管理器性能网络监控数据的方法详解》在现代操作系统中,任务管理器是一个非常重要的工具,用于监控和管理计算机的运行状态,包括CPU使用率、内存占用等,对于开发者和系统管理员来说,了解这些... 目录引言一、背景知识二、准备工作1. Maven依赖2. Gradle依赖三、代码实现四、代码详解五

java如何分布式锁实现和选型

《java如何分布式锁实现和选型》文章介绍了分布式锁的重要性以及在分布式系统中常见的问题和需求,它详细阐述了如何使用分布式锁来确保数据的一致性和系统的高可用性,文章还提供了基于数据库、Redis和Zo... 目录引言:分布式锁的重要性与分布式系统中的常见问题和需求分布式锁的重要性分布式系统中常见的问题和需求

SpringBoot基于MyBatis-Plus实现Lambda Query查询的示例代码

《SpringBoot基于MyBatis-Plus实现LambdaQuery查询的示例代码》MyBatis-Plus是MyBatis的增强工具,简化了数据库操作,并提高了开发效率,它提供了多种查询方... 目录引言基础环境配置依赖配置(Maven)application.yml 配置表结构设计demo_st

如何使用celery进行异步处理和定时任务(django)

《如何使用celery进行异步处理和定时任务(django)》文章介绍了Celery的基本概念、安装方法、如何使用Celery进行异步任务处理以及如何设置定时任务,通过Celery,可以在Web应用中... 目录一、celery的作用二、安装celery三、使用celery 异步执行任务四、使用celery

使用Python绘制蛇年春节祝福艺术图

《使用Python绘制蛇年春节祝福艺术图》:本文主要介绍如何使用Python的Matplotlib库绘制一幅富有创意的“蛇年有福”艺术图,这幅图结合了数字,蛇形,花朵等装饰,需要的可以参考下... 目录1. 绘图的基本概念2. 准备工作3. 实现代码解析3.1 设置绘图画布3.2 绘制数字“2025”3.3

在Ubuntu上部署SpringBoot应用的操作步骤

《在Ubuntu上部署SpringBoot应用的操作步骤》随着云计算和容器化技术的普及,Linux服务器已成为部署Web应用程序的主流平台之一,Java作为一种跨平台的编程语言,具有广泛的应用场景,本... 目录一、部署准备二、安装 Java 环境1. 安装 JDK2. 验证 Java 安装三、安装 mys

Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单

《Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单》:本文主要介绍Springboot的ThreadPoolTaskScheduler线... 目录ThreadPoolTaskScheduler线程池实现15分钟不操作自动取消订单概要1,创建订单后

详谈redis跟数据库的数据同步问题

《详谈redis跟数据库的数据同步问题》文章讨论了在Redis和数据库数据一致性问题上的解决方案,主要比较了先更新Redis缓存再更新数据库和先更新数据库再更新Redis缓存两种方案,文章指出,删除R... 目录一、Redis 数据库数据一致性的解决方案1.1、更新Redis缓存、删除Redis缓存的区别二