【问题标题】:C# Json extract a list of values from a Json list or arrayC# Json 从 Json 列表或数组中提取值列表
【发布时间】:2022-01-10 17:03:31
【问题描述】:

我想从“scanEvents”列表或数组中提取值。每个 scanEvent 都有一个日期、事件类型、事件描述、派生状态等...

我已经使用了几种方法,例如下面的这个,但到目前为止我无法提取每个“scanEvent”的值

 var data = (JObject)JsonConvert.DeserializeObject(strFedExJSON);
            
            var scanevents = data["scanEvents"];

            var output = scanevents.Children<JProperty>()
                                 .Select(prop => prop.Value.ToObject<Scanevent>())
                                 .ToList();

           foreach (var x in output)
            {
                richTextBox1.Text += output + Environment.NewLine;
            }

我想在下面得到这种输出:

 "date": "2021-12-22T15:14:00-10:00", "eventDescription": "Delivered", "city": "HILO",    "stateOrProvinceCode": "HI", "countryCode": "US", "locationType": "DELIVERY_LOCATION",  "derivedStatus": "Delivered"


 "date": "2021-12-22T14:40:00-10:00", "eventDescription": "On FedEx vehicle for delivery", "city": "HILO","stateOrProvinceCode": "HI","countryCode": "US",    "locationType": "VEHICLE", "derivedStatus": "In transit"  


 "date": "2021-12-22T14:37:00-10:00","eventDescription": "At local FedEx facility","city":  "countryCode": "US","HILO",  "locationType": "DESTINATION_FEDEX_FACILITY",  "derivedStatus": "In transit"
                        

如何提取下面“scanEvents”列表中每个事件的值(日期、事件描述、派生状态)?这个似乎被埋在了几种类型或对象之下。

{
    "transactionId": "44d2c2a9-1204-4ff7-94f3-ae8699257f77",
    "output": {
        "completeTrackResults": [
            {
                "trackingNumber": "673247499414",
                "trackResults": [
                    {
                        "trackingNumberInfo": {
                            "trackingNumber": "673247499414",
                            "trackingNumberUniqueId": "2459570000~673247499414~FX",
                            "carrierCode": "FDXE"
                        },
                        "additionalTrackingInfo": {
                            "nickname": "",
                            "packageIdentifiers": [
                                {
                                    "type": "DEPARTMENT",
                                    "values": [
                                        "32 MQ"
                                    ],
                                    "trackingNumberUniqueId": "",
                                    "carrierCode": ""
                                },
                                {
                                    "type": "SHIPPER_REFERENCE",
                                    "values": [
                                        "6033245/O956871"
                                    ],
                                    "trackingNumberUniqueId": "",
                                    "carrierCode": ""
                                }
                            ],
                            "hasAssociatedShipments": false
                        },
                        "shipperInformation": {
                            "contact": {},
                            "address": {
                                "city": "MIRA LOMA",
                                "stateOrProvinceCode": "CA",
                                "countryCode": "US",
                                "residential": false,
                                "countryName": "United States"
                            }
                        },
                        "recipientInformation": {
                            "contact": {},
                            "address": {
                                "city": "HILO",
                                "stateOrProvinceCode": "HI",
                                "countryCode": "US",
                                "residential": false,
                                "countryName": "United States"
                            }
                        },
                        "latestStatusDetail": {
                            "code": "DL",
                            "derivedCode": "DL",
                            "statusByLocale": "Delivered",
                            "description": "Delivered",
                            "scanLocation": {
                                "city": "HILO",
                                "stateOrProvinceCode": "HI",
                                "countryCode": "US",
                                "residential": false,
                                "countryName": "United States"
                            }
                        },
                        "dateAndTimes": [
                            {
                                "type": "ACTUAL_DELIVERY",
                                "dateTime": "2021-12-22T15:14:00-10:00"
                            },
                            {
                                "type": "ACTUAL_PICKUP",
                                "dateTime": "2021-12-21T18:12:00-08:00"
                            },
                            {
                                "type": "SHIP",
                                "dateTime": "2021-12-21T00:00:00-06:00"
                            },
                            {
                                "type": "ACTUAL_TENDER",
                                "dateTime": "2021-12-21T18:14:00-08:00"
                            }
                        ],
                        "availableImages": [
                            {
                                "type": "SIGNATURE_PROOF_OF_DELIVERY"
                            }
                        ],
                        "specialHandlings": [
                            {
                                "type": "DELIVER_WEEKDAY",
                                "description": "Deliver Weekday",
                                "paymentType": "OTHER"
                            }
                        ],
                        "packageDetails": {
                            "packagingDescription": {
                                "type": "YOUR_PACKAGING",
                                "description": "Your Packaging"
                            },
                            "sequenceNumber": "1",
                            "count": "1",
                            "weightAndDimensions": {
                                "weight": [
                                    {
                                        "value": "10.0",
                                        "unit": "LB"
                                    },
                                    {
                                        "value": "4.54",
                                        "unit": "KG"
                                    }
                                ],
                                "dimensions": [
                                    {
                                        "length": 20,
                                        "width": 12,
                                        "height": 13,
                                        "units": "IN"
                                    },
                                    {
                                        "length": 50,
                                        "width": 30,
                                        "height": 33,
                                        "units": "CM"
                                    }
                                ]
                            },
                            "packageContent": []
                        },
                        "shipmentDetails": {
                            "possessionStatus": true,
                            "weight": [
                                {
                                    "value": "10.0",
                                    "unit": "LB"
                                },
                                {
                                    "value": "4.54",
                                    "unit": "KG"
                                }
                            ]
                        },
                        "scanEvents": [
                            {
                                "date": "2021-12-22T15:14:00-10:00",
                                "eventType": "DL",
                                "eventDescription": "Delivered",
                                "exceptionCode": "",
                                "exceptionDescription": "",
                                "scanLocation": {
                                    "streetLines": [
                                        ""
                                    ],
                                    "city": "HILO",
                                    "stateOrProvinceCode": "HI",
                                    "postalCode": "96720",
                                    "countryCode": "US",
                                    "residential": false,
                                    "countryName": "United States"
                                },
                                "locationId": "ITOA",
                                "locationType": "DELIVERY_LOCATION",
                                "derivedStatusCode": "DL",
                                "derivedStatus": "Delivered"
                            },
                            {
                                "date": "2021-12-22T14:40:00-10:00",
                                "eventType": "OD",
                                "eventDescription": "On FedEx vehicle for delivery",
                                "exceptionCode": "",
                                "exceptionDescription": "",
                                "scanLocation": {
                                    "streetLines": [
                                        ""
                                    ],
                                    "city": "HILO",
                                    "stateOrProvinceCode": "HI",
                                    "postalCode": "96720",
                                    "countryCode": "US",
                                    "residential": false,
                                    "countryName": "United States"
                                },
                                "locationId": "ITOA",
                                "locationType": "VEHICLE",
                                "derivedStatusCode": "IT",
                                "derivedStatus": "In transit"
                            },
                            {
                                "date": "2021-12-22T14:37:00-10:00",
                                "eventType": "AR",
                                "eventDescription": "At local FedEx facility",
                                "exceptionCode": "",
                                "exceptionDescription": "",
                                "scanLocation": {
                                    "streetLines": [
                                        ""
                                    ],
                                    "city": "HILO",
                                    "stateOrProvinceCode": "HI",
                                    "postalCode": "96720",
                                    "countryCode": "US",
                                    "residential": false,
                                    "countryName": "United States"
                                },
                                "locationId": "ITOA",
                                "locationType": "DESTINATION_FEDEX_FACILITY",
                                "derivedStatusCode": "IT",
                                "derivedStatus": "In transit"
                            },
                            {
                                "date": "2021-12-22T07:35:00-10:00",
                                "eventType": "AR",
                                "eventDescription": "At destination sort facility",
                                "exceptionCode": "",
                                "exceptionDescription": "",
                                "scanLocation": {
                                    "streetLines": [
                                        ""
                                    ],
                                    "city": "HONOLULU",
                                    "stateOrProvinceCode": "HI",
                                    "postalCode": "96819",
                                    "countryCode": "US",
                                    "residential": false,
                                    "countryName": "United States"
                                },
                                "locationId": "HNLR",
                                "locationType": "SORT_FACILITY",
                                "derivedStatusCode": "IT",
                                "derivedStatus": "In transit"
                            },
                            {
                                "date": "2021-12-22T04:21:00-08:00",
                                "eventType": "DP",
                                "eventDescription": "Departed FedEx hub",
                                "exceptionCode": "",
                                "exceptionDescription": "",
                                "scanLocation": {
                                    "streetLines": [
                                        ""
                                    ],
                                    "city": "OAKLAND",
                                    "stateOrProvinceCode": "CA",
                                    "postalCode": "94621",
                                    "countryCode": "US",
                                    "residential": false,
                                    "countryName": "United States"
                                },
                                "locationId": "OAKH",
                                "locationType": "FEDEX_FACILITY",
                                "derivedStatusCode": "IT",
                                "derivedStatus": "In transit"
                            },
                            {
                                "date": "2021-12-21T23:27:00-08:00",
                                "eventType": "AR",
                                "eventDescription": "Arrived at FedEx hub",
                                "exceptionCode": "",
                                "exceptionDescription": "",
                                "scanLocation": {
                                    "streetLines": [
                                        ""
                                    ],
                                    "city": "OAKLAND",
                                    "stateOrProvinceCode": "CA",
                                    "postalCode": "94621",
                                    "countryCode": "US",
                                    "residential": false,
                                    "countryName": "United States"
                                },
                                "locationId": "OAKH",
                                "locationType": "FEDEX_FACILITY",
                                "derivedStatusCode": "IT",
                                "derivedStatus": "In transit"
                            },
                            {
                                "date": "2021-12-21T19:13:00-08:00",
                                "eventType": "DP",
                                "eventDescription": "Left FedEx origin facility",
                                "exceptionCode": "",
                                "exceptionDescription": "",
                                "scanLocation": {
                                    "streetLines": [
                                        ""
                                    ],
                                    "city": "ONTARIO",
                                    "stateOrProvinceCode": "CA",
                                    "postalCode": "91761",
                                    "countryCode": "US",
                                    "residential": false,
                                    "countryName": "United States"
                                },
                                "locationId": "ONTA",
                                "locationType": "ORIGIN_FEDEX_FACILITY",
                                "derivedStatusCode": "IT",
                                "derivedStatus": "In transit"
                            },
                            {
                                "date": "2021-12-21T18:12:00-08:00",
                                "eventType": "PU",
                                "eventDescription": "Picked up",
                                "exceptionCode": "",
                                "exceptionDescription": "",
                                "scanLocation": {
                                    "streetLines": [
                                        ""
                                    ],
                                    "city": "ONTARIO",
                                    "stateOrProvinceCode": "CA",
                                    "postalCode": "91761",
                                    "countryCode": "US",
                                    "residential": false,
                                    "countryName": "United States"
                                },
                                "locationId": "ONTA",
                                "locationType": "PICKUP_LOCATION",
                                "derivedStatusCode": "PU",
                                "derivedStatus": "Picked up"
                            },
                            {
                                "date": "2021-12-21T16:55:06-06:00",
                                "eventType": "OC",
                                "eventDescription": "Shipment information sent to FedEx",
                                "exceptionCode": "",
                                "exceptionDescription": "",
                                "scanLocation": {
                                    "streetLines": [
                                        ""
                                    ],
                                    "residential": false
                                },
                                "locationType": "CUSTOMER",
                                "derivedStatusCode": "IN",
                                "derivedStatus": "Initiated"
                            }
                        ],
                        "availableNotifications": [
                            "ON_DELIVERY"
                        ],
                        "deliveryDetails": {
                            "actualDeliveryAddress": {
                                "city": "HILO",
                                "stateOrProvinceCode": "HI",
                                "countryCode": "US",
                                "residential": false,
                                "countryName": "United States"
                            },
                            "locationType": "SHIPPING_RECEIVING",
                            "locationDescription": "Shipping/Receiving",
                            "deliveryAttempts": "0",
                            "receivedByName": "L.WEAVER",
                            "deliveryOptionEligibilityDetails": [
                                {
                                    "option": "INDIRECT_SIGNATURE_RELEASE",
                                    "eligibility": "INELIGIBLE"
                                },
                                {
                                    "option": "REDIRECT_TO_HOLD_AT_LOCATION",
                                    "eligibility": "INELIGIBLE"
                                },
                                {
                                    "option": "REROUTE",
                                    "eligibility": "INELIGIBLE"
                                },
                                {
                                    "option": "RESCHEDULE",
                                    "eligibility": "INELIGIBLE"
                                },
                                {
                                    "option": "RETURN_TO_SHIPPER",
                                    "eligibility": "INELIGIBLE"
                                },
                                {
                                    "option": "DISPUTE_DELIVERY",
                                    "eligibility": "INELIGIBLE"
                                },
                                {
                                    "option": "SUPPLEMENT_ADDRESS",
                                    "eligibility": "INELIGIBLE"
                                }
                            ]
                        },
                        "originLocation": {
                            "locationContactAndAddress": {
                                "address": {
                                    "city": "ONTARIO",
                                    "stateOrProvinceCode": "CA",
                                    "countryCode": "US",
                                    "residential": false,
                                    "countryName": "United States"
                                }
                            },
                            "locationId": "ONTA"
                        },
                        "destinationLocation": {
                            "locationContactAndAddress": {
                                "address": {
                                    "city": "HILO",
                                    "stateOrProvinceCode": "HI",
                                    "countryCode": "US",
                                    "residential": false,
                                    "countryName": "United States"
                                }
                            },
                            "locationType": ""
                        },
                        "lastUpdatedDestinationAddress": {
                            "city": "HILO",
                            "stateOrProvinceCode": "HI",
                            "countryCode": "US",
                            "residential": false,
                            "countryName": "United States"
                        },
                        "serviceDetail": {
                            "type": "PRIORITY_OVERNIGHT",
                            "description": "FedEx Priority Overnight",
                            "shortDescription": "PO"
                        },
                        "standardTransitTimeWindow": {
                            "window": {
                                "ends": "2021-12-22T17:00:00-10:00"
                            }
                        },
                        "estimatedDeliveryTimeWindow": {
                            "window": {}
                        },
                        "goodsClassificationCode": "",
                        "returnDetail": {}
                    }
                ]
            }
        ]
    }
}

【问题讨论】:

  • 在我看来,当 json 包含多个 trackResults 时,您可能有多个 scanEvents。所以没有明确的路径。最后的输出应该包含 trackingNumber,这样你就知道在这种情况下事件属于哪里。我要做的是创建真正的类来将 json 序列化为(使用 json 到类转换器)。这在代码中更容易理解,并且您可以更轻松地在类树中导航并从中创建有意义的输出字符串。
  • 你可以考虑自动创建一个类,它可以让你循环遍历它的 stronly 类型属性;见stackoverflow.com/a/48023576/4180382

标签: c# arrays json list


【解决方案1】:

你可以试试这样的

var jsonObject = JObject.Parse(strFedExJSON); 

 var scanEventsJson= jsonObject["output"]["completeTrackResults"][0]["trackResults"][0] ["scanEvents"].ToString();

输出

  {
    "date": "2021-12-22T21:44:00-03:30",
    "eventType": "DL",
    "eventDescription": "Delivered",
    "exceptionCode": "",
    "exceptionDescription": "",
    "scanLocation": {
      "streetLines": [
        ""
      ],
      "city": "HILO",
      "stateOrProvinceCode": "HI",
      "postalCode": "96720",
      "countryCode": "US",
      "residential": false,
      "countryName": "United States"
    },
    "locationId": "ITOA",
    "locationType": "DELIVERY_LOCATION",
    "derivedStatusCode": "DL",
    "derivedStatus": "Delivered"
  },
  {
    "date": "2021-12-22T21:10:00-03:30",
    "eventType": "OD",
    "eventDescription": "On FedEx vehicle for delivery",
    "exceptionCode": "",
    "exceptionDescription": "",
    "scanLocation": {
      "streetLines": [
        ""
      ],
      "city": "HILO",
      "stateOrProvinceCode": "HI",
      "postalCode": "96720",
      "countryCode": "US",
      "residential": false,
      "countryName": "United States"
    },
    "locationId": "ITOA",
    "locationType": "VEHICLE",
    "derivedStatusCode": "IT",
    "derivedStatus": "In transit"
  },
  {
    "date": "2021-12-22T21:07:00-03:30",
    "eventType": "AR",
    "eventDescription": "At local FedEx facility",
    "exceptionCode": "",
    "exceptionDescription": "",
    "scanLocation": {
      "streetLines": [
        ""
      ],
      "city": "HILO",
      "stateOrProvinceCode": "HI",
      "postalCode": "96720",
      "countryCode": "US",
      "residential": false,
      "countryName": "United States"
    },
    "locationId": "ITOA",
    "locationType": "DESTINATION_FEDEX_FACILITY",
    "derivedStatusCode": "IT",
    "derivedStatus": "In transit"
  },
  {
    "date": "2021-12-22T14:05:00-03:30",
    "eventType": "AR",
    "eventDescription": "At destination sort facility",
    "exceptionCode": "",
    "exceptionDescription": "",
    "scanLocation": {
      "streetLines": [
        ""
      ],
      "city": "HONOLULU",
      "stateOrProvinceCode": "HI",
      "postalCode": "96819",
      "countryCode": "US",
      "residential": false,
      "countryName": "United States"
    },
    "locationId": "HNLR",
    "locationType": "SORT_FACILITY",
    "derivedStatusCode": "IT",
    "derivedStatus": "In transit"
  },
  {
    "date": "2021-12-22T08:51:00-03:30",
    "eventType": "DP",
    "eventDescription": "Departed FedEx hub",
    "exceptionCode": "",
    "exceptionDescription": "",
    "scanLocation": {
      "streetLines": [
        ""
      ],
      "city": "OAKLAND",
      "stateOrProvinceCode": "CA",
      "postalCode": "94621",
      "countryCode": "US",
      "residential": false,
      "countryName": "United States"
    },
    "locationId": "OAKH",
    "locationType": "FEDEX_FACILITY",
    "derivedStatusCode": "IT",
    "derivedStatus": "In transit"
  },
  {
    "date": "2021-12-22T03:57:00-03:30",
    "eventType": "AR",
    "eventDescription": "Arrived at FedEx hub",
    "exceptionCode": "",
    "exceptionDescription": "",
    "scanLocation": {
      "streetLines": [
        ""
      ],
      "city": "OAKLAND",
      "stateOrProvinceCode": "CA",
      "postalCode": "94621",
      "countryCode": "US",
      "residential": false,
      "countryName": "United States"
    },
    "locationId": "OAKH",
    "locationType": "FEDEX_FACILITY",
    "derivedStatusCode": "IT",
    "derivedStatus": "In transit"
  },
  {
    "date": "2021-12-21T23:43:00-03:30",
    "eventType": "DP",
    "eventDescription": "Left FedEx origin facility",
    "exceptionCode": "",
    "exceptionDescription": "",
    "scanLocation": {
      "streetLines": [
        ""
      ],
      "city": "ONTARIO",
      "stateOrProvinceCode": "CA",
      "postalCode": "91761",
      "countryCode": "US",
      "residential": false,
      "countryName": "United States"
    },
    "locationId": "ONTA",
    "locationType": "ORIGIN_FEDEX_FACILITY",
    "derivedStatusCode": "IT",
    "derivedStatus": "In transit"
  },
  {
    "date": "2021-12-21T22:42:00-03:30",
    "eventType": "PU",
    "eventDescription": "Picked up",
    "exceptionCode": "",
    "exceptionDescription": "",
    "scanLocation": {
      "streetLines": [
        ""
      ],
      "city": "ONTARIO",
      "stateOrProvinceCode": "CA",
      "postalCode": "91761",
      "countryCode": "US",
      "residential": false,
      "countryName": "United States"
    },
    "locationId": "ONTA",
    "locationType": "PICKUP_LOCATION",
    "derivedStatusCode": "PU",
    "derivedStatus": "Picked up"
  },
  {
    "date": "2021-12-21T19:25:06-03:30",
    "eventType": "OC",
    "eventDescription": "Shipment information sent to FedEx",
    "exceptionCode": "",
    "exceptionDescription": "",
    "scanLocation": {
      "streetLines": [
        ""
      ],
      "residential": false
    },
    "locationType": "CUSTOMER",
    "derivedStatusCode": "IN",
    "derivedStatus": "Initiated"
  }
]

如果你需要,我可以把它写成一行,但它会更难阅读。

foreach (var completeTrackResult in jsonObject["output"]["completeTrackResults"])
{
    foreach (var trackResult in completeTrackResult["trackResults"])
    {
        foreach (var scanEvent in trackResult["scanEvents"])
        {
            Console.WriteLine(JsonConvert.SerializeObject(scanEvent) + "\n\r");
        }
    }
}

输出

{"date":"2021-12-22T21:44:00-03:30","eventType":"DL","eventDescription":"Delivered","exceptionCode":"","exceptionDescription":"","scanLocation":{"streetLines":[""],"city":"HILO","stateOrProvinceCode":"HI","postalCode":"96720","countryCode":"US","residential":false,"countryName":"United States"},"locationId":"ITOA","locationType":"DELIVERY_LOCATION","derivedStatusCode":"DL","derivedStatus":"Delivered"}

{"date":"2021-12-22T21:10:00-03:30","eventType":"OD","eventDescription":"On FedEx vehicle for delivery","exceptionCode":"","exceptionDescription":"","scanLocation":{"streetLines":[""],"city":"HILO","stateOrProvinceCode":"HI","postalCode":"96720","countryCode":"US","residential":false,"countryName":"United States"},"locationId":"ITOA","locationType":"VEHICLE","derivedStatusCode":"IT","derivedStatus":"In transit"}

{"date":"2021-12-22T21:07:00-03:30","eventType":"AR","eventDescription":"At local FedEx facility","exceptionCode":"","exceptionDescription":"","scanLocation":{"streetLines":[""],"city":"HILO","stateOrProvinceCode":"HI","postalCode":"96720","countryCode":"US","residential":false,"countryName":"United States"},"locationId":"ITOA","locationType":"DESTINATION_FEDEX_FACILITY","derivedStatusCode":"IT","derivedStatus":"In transit"}

{"date":"2021-12-22T14:05:00-03:30","eventType":"AR","eventDescription":"At destination sort facility","exceptionCode":"","exceptionDescription":"","scanLocation":{"streetLines":[""],"city":"HONOLULU","stateOrProvinceCode":"HI","postalCode":"96819","countryCode":"US","residential":false,"countryName":"United States"},"locationId":"HNLR","locationType":"SORT_FACILITY","derivedStatusCode":"IT","derivedStatus":"In transit"}

{"date":"2021-12-22T08:51:00-03:30","eventType":"DP","eventDescription":"Departed FedEx hub","exceptionCode":"","exceptionDescription":"","scanLocation":{"streetLines":[""],"city":"OAKLAND","stateOrProvinceCode":"CA","postalCode":"94621","countryCode":"US","residential":false,"countryName":"United States"},"locationId":"OAKH","locationType":"FEDEX_FACILITY","derivedStatusCode":"IT","derivedStatus":"In transit"}

{"date":"2021-12-22T03:57:00-03:30","eventType":"AR","eventDescription":"Arrived at FedEx hub","exceptionCode":"","exceptionDescription":"","scanLocation":{"streetLines":[""],"city":"OAKLAND","stateOrProvinceCode":"CA","postalCode":"94621","countryCode":"US","residential":false,"countryName":"United States"},"locationId":"OAKH","locationType":"FEDEX_FACILITY","derivedStatusCode":"IT","derivedStatus":"In transit"}

{"date":"2021-12-21T23:43:00-03:30","eventType":"DP","eventDescription":"Left FedEx origin facility","exceptionCode":"","exceptionDescription":"","scanLocation":{"streetLines":[""],"city":"ONTARIO","stateOrProvinceCode":"CA","postalCode":"91761","countryCode":"US","residential":false,"countryName":"United States"},"locationId":"ONTA","locationType":"ORIGIN_FEDEX_FACILITY","derivedStatusCode":"IT","derivedStatus":"In transit"}

{"date":"2021-12-21T22:42:00-03:30","eventType":"PU","eventDescription":"Picked up","exceptionCode":"","exceptionDescription":"","scanLocation":{"streetLines":[""],"city":"ONTARIO","stateOrProvinceCode":"CA","postalCode":"91761","countryCode":"US","residential":false,"countryName":"United States"},"locationId":"ONTA","locationType":"PICKUP_LOCATION","derivedStatusCode":"PU","derivedStatus":"Picked up"}

{"date":"2021-12-21T19:25:06-03:30","eventType":"OC","eventDescription":"Shipment information sent to FedEx","exceptionCode":"","exceptionDescription":"","scanLocation":{"streetLines":[""],"residential":false},"locationType":"CUSTOMER","derivedStatusCode":"IN","derivedStatus":"Initiated"}

【讨论】:

    【解决方案2】:

    因此,正如其他人所评论的(我的感受是一致的),只要我们对某些 JSON 事物进行合理数量的处理,将 JSON 解析为对象并使用这些对象就更容易了。我(个人,无从属关系)前往 https://quicktype.io 并将 JSON 粘贴到那里,以生成一组类:

    // <auto-generated />
    //
    // To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
    //
    //    using HackyTracky;
    //
    //    var trackyThing = TrackyThing.FromJson(jsonString);
    
    namespace HackyTracky
    {
        using System;
        using System.Collections.Generic;
    
        using System.Globalization;
        using Newtonsoft.Json;
        using Newtonsoft.Json.Converters;
    
        public partial class TrackyThing
        {
            [JsonProperty("transactionId")]
            public Guid TransactionId { get; set; }
    
            [JsonProperty("output")]
            public Output Output { get; set; }
        }
    
        public partial class Output
        {
            [JsonProperty("completeTrackResults")]
            public CompleteTrackResult[] CompleteTrackResults { get; set; }
        }
    
        public partial class CompleteTrackResult
        {
            [JsonProperty("trackingNumber")]
            public string TrackingNumber { get; set; }
    
            [JsonProperty("trackResults")]
            public TrackResult[] TrackResults { get; set; }
        }
    
        public partial class TrackResult
        {
            [JsonProperty("trackingNumberInfo")]
            public TrackingNumberInfo TrackingNumberInfo { get; set; }
    
            [JsonProperty("additionalTrackingInfo")]
            public AdditionalTrackingInfo AdditionalTrackingInfo { get; set; }
    
            [JsonProperty("shipperInformation")]
            public Information ShipperInformation { get; set; }
    
            [JsonProperty("recipientInformation")]
            public Information RecipientInformation { get; set; }
    
            [JsonProperty("latestStatusDetail")]
            public LatestStatusDetail LatestStatusDetail { get; set; }
    
            [JsonProperty("dateAndTimes")]
            public DateAndTime[] DateAndTimes { get; set; }
    
            [JsonProperty("availableImages")]
            public AvailableImage[] AvailableImages { get; set; }
    
            [JsonProperty("specialHandlings")]
            public SpecialHandling[] SpecialHandlings { get; set; }
    
            [JsonProperty("packageDetails")]
            public PackageDetails PackageDetails { get; set; }
    
            [JsonProperty("shipmentDetails")]
            public ShipmentDetails ShipmentDetails { get; set; }
    
            [JsonProperty("scanEvents")]
            public ScanEvent[] ScanEvents { get; set; }
    
            [JsonProperty("availableNotifications")]
            public string[] AvailableNotifications { get; set; }
    
            [JsonProperty("deliveryDetails")]
            public DeliveryDetails DeliveryDetails { get; set; }
    
            [JsonProperty("originLocation")]
            public OriginLocation OriginLocation { get; set; }
    
            [JsonProperty("destinationLocation")]
            public DestinationLocation DestinationLocation { get; set; }
    
            [JsonProperty("lastUpdatedDestinationAddress")]
            public LastUpdatedDestinationAddress LastUpdatedDestinationAddress { get; set; }
    
            [JsonProperty("serviceDetail")]
            public ServiceDetail ServiceDetail { get; set; }
    
            [JsonProperty("standardTransitTimeWindow")]
            public StandardTransitTimeWindow StandardTransitTimeWindow { get; set; }
    
            [JsonProperty("estimatedDeliveryTimeWindow")]
            public EstimatedDeliveryTimeWindow EstimatedDeliveryTimeWindow { get; set; }
    
            [JsonProperty("goodsClassificationCode")]
            public string GoodsClassificationCode { get; set; }
    
            [JsonProperty("returnDetail")]
            public ReturnDetail ReturnDetail { get; set; }
        }
    
        public partial class AdditionalTrackingInfo
        {
            [JsonProperty("nickname")]
            public string Nickname { get; set; }
    
            [JsonProperty("packageIdentifiers")]
            public PackageIdentifier[] PackageIdentifiers { get; set; }
    
            [JsonProperty("hasAssociatedShipments")]
            public bool HasAssociatedShipments { get; set; }
        }
    
        public partial class PackageIdentifier
        {
            [JsonProperty("type")]
            public string Type { get; set; }
    
            [JsonProperty("values")]
            public string[] Values { get; set; }
    
            [JsonProperty("trackingNumberUniqueId")]
            public string TrackingNumberUniqueId { get; set; }
    
            [JsonProperty("carrierCode")]
            public string CarrierCode { get; set; }
        }
    
        public partial class AvailableImage
        {
            [JsonProperty("type")]
            public string Type { get; set; }
        }
    
        public partial class DateAndTime
        {
            [JsonProperty("type")]
            public string Type { get; set; }
    
            [JsonProperty("dateTime")]
            public DateTimeOffset DateTime { get; set; }
        }
    
        public partial class DeliveryDetails
        {
            [JsonProperty("actualDeliveryAddress")]
            public LastUpdatedDestinationAddress ActualDeliveryAddress { get; set; }
    
            [JsonProperty("locationType")]
            public string LocationType { get; set; }
    
            [JsonProperty("locationDescription")]
            public string LocationDescription { get; set; }
    
            [JsonProperty("deliveryAttempts")]
            [JsonConverter(typeof(ParseStringConverter))]
            public long DeliveryAttempts { get; set; }
    
            [JsonProperty("receivedByName")]
            public string ReceivedByName { get; set; }
    
            [JsonProperty("deliveryOptionEligibilityDetails")]
            public DeliveryOptionEligibilityDetail[] DeliveryOptionEligibilityDetails { get; set; }
        }
    
        public partial class LastUpdatedDestinationAddress
        {
            [JsonProperty("city")]
            public string City { get; set; }
    
            [JsonProperty("stateOrProvinceCode")]
            public string StateOrProvinceCode { get; set; }
    
            [JsonProperty("countryCode")]
            public string CountryCode { get; set; }
    
            [JsonProperty("residential")]
            public bool Residential { get; set; }
    
            [JsonProperty("countryName")]
            public string CountryName { get; set; }
        }
    
        public partial class DeliveryOptionEligibilityDetail
        {
            [JsonProperty("option")]
            public string Option { get; set; }
    
            [JsonProperty("eligibility")]
            public string Eligibility { get; set; }
        }
    
        public partial class DestinationLocation
        {
            [JsonProperty("locationContactAndAddress")]
            public LocationContactAndAddress LocationContactAndAddress { get; set; }
    
            [JsonProperty("locationType")]
            public string LocationType { get; set; }
        }
    
        public partial class LocationContactAndAddress
        {
            [JsonProperty("address")]
            public LastUpdatedDestinationAddress Address { get; set; }
        }
    
        public partial class EstimatedDeliveryTimeWindow
        {
            [JsonProperty("window")]
            public ReturnDetail Window { get; set; }
        }
    
        public partial class ReturnDetail
        {
        }
    
        public partial class LatestStatusDetail
        {
            [JsonProperty("code")]
            public string Code { get; set; }
    
            [JsonProperty("derivedCode")]
            public string DerivedCode { get; set; }
    
            [JsonProperty("statusByLocale")]
            public string StatusByLocale { get; set; }
    
            [JsonProperty("description")]
            public string Description { get; set; }
    
            [JsonProperty("scanLocation")]
            public LastUpdatedDestinationAddress ScanLocation { get; set; }
        }
    
        public partial class OriginLocation
        {
            [JsonProperty("locationContactAndAddress")]
            public LocationContactAndAddress LocationContactAndAddress { get; set; }
    
            [JsonProperty("locationId")]
            public string LocationId { get; set; }
        }
    
        public partial class PackageDetails
        {
            [JsonProperty("packagingDescription")]
            public PackagingDescription PackagingDescription { get; set; }
    
            [JsonProperty("sequenceNumber")]
            [JsonConverter(typeof(ParseStringConverter))]
            public long SequenceNumber { get; set; }
    
            [JsonProperty("count")]
            [JsonConverter(typeof(ParseStringConverter))]
            public long Count { get; set; }
    
            [JsonProperty("weightAndDimensions")]
            public WeightAndDimensions WeightAndDimensions { get; set; }
    
            [JsonProperty("packageContent")]
            public object[] PackageContent { get; set; }
        }
    
        public partial class PackagingDescription
        {
            [JsonProperty("type")]
            public string Type { get; set; }
    
            [JsonProperty("description")]
            public string Description { get; set; }
        }
    
        public partial class WeightAndDimensions
        {
            [JsonProperty("weight")]
            public Weight[] Weight { get; set; }
    
            [JsonProperty("dimensions")]
            public Dimension[] Dimensions { get; set; }
        }
    
        public partial class Dimension
        {
            [JsonProperty("length")]
            public long Length { get; set; }
    
            [JsonProperty("width")]
            public long Width { get; set; }
    
            [JsonProperty("height")]
            public long Height { get; set; }
    
            [JsonProperty("units")]
            public string Units { get; set; }
        }
    
        public partial class Weight
        {
            [JsonProperty("value")]
            public string Value { get; set; }
    
            [JsonProperty("unit")]
            public string Unit { get; set; }
        }
    
        public partial class Information
        {
            [JsonProperty("contact")]
            public ReturnDetail Contact { get; set; }
    
            [JsonProperty("address")]
            public LastUpdatedDestinationAddress Address { get; set; }
        }
    
        public partial class ScanEvent
        {
            [JsonProperty("date")]
            public DateTimeOffset Date { get; set; }
    
            [JsonProperty("eventType")]
            public string EventType { get; set; }
    
            [JsonProperty("eventDescription")]
            public string EventDescription { get; set; }
    
            [JsonProperty("exceptionCode")]
            public string ExceptionCode { get; set; }
    
            [JsonProperty("exceptionDescription")]
            public string ExceptionDescription { get; set; }
    
            [JsonProperty("scanLocation")]
            public ScanLocation ScanLocation { get; set; }
    
            [JsonProperty("locationId", NullValueHandling = NullValueHandling.Ignore)]
            public string LocationId { get; set; }
    
            [JsonProperty("locationType")]
            public string LocationType { get; set; }
    
            [JsonProperty("derivedStatusCode")]
            public string DerivedStatusCode { get; set; }
    
            [JsonProperty("derivedStatus")]
            public string DerivedStatus { get; set; }
        }
    
        public partial class ScanLocation
        {
            [JsonProperty("streetLines")]
            public string[] StreetLines { get; set; }
    
            [JsonProperty("city", NullValueHandling = NullValueHandling.Ignore)]
            public string City { get; set; }
    
            [JsonProperty("stateOrProvinceCode", NullValueHandling = NullValueHandling.Ignore)]
            public string StateOrProvinceCode { get; set; }
    
            [JsonProperty("postalCode", NullValueHandling = NullValueHandling.Ignore)]
            [JsonConverter(typeof(ParseStringConverter))]
            public long? PostalCode { get; set; }
    
            [JsonProperty("countryCode", NullValueHandling = NullValueHandling.Ignore)]
            public string CountryCode { get; set; }
    
            [JsonProperty("residential")]
            public bool Residential { get; set; }
    
            [JsonProperty("countryName", NullValueHandling = NullValueHandling.Ignore)]
            public string CountryName { get; set; }
        }
    
        public partial class ServiceDetail
        {
            [JsonProperty("type")]
            public string Type { get; set; }
    
            [JsonProperty("description")]
            public string Description { get; set; }
    
            [JsonProperty("shortDescription")]
            public string ShortDescription { get; set; }
        }
    
        public partial class ShipmentDetails
        {
            [JsonProperty("possessionStatus")]
            public bool PossessionStatus { get; set; }
    
            [JsonProperty("weight")]
            public Weight[] Weight { get; set; }
        }
    
        public partial class SpecialHandling
        {
            [JsonProperty("type")]
            public string Type { get; set; }
    
            [JsonProperty("description")]
            public string Description { get; set; }
    
            [JsonProperty("paymentType")]
            public string PaymentType { get; set; }
        }
    
        public partial class StandardTransitTimeWindow
        {
            [JsonProperty("window")]
            public Window Window { get; set; }
        }
    
        public partial class Window
        {
            [JsonProperty("ends")]
            public DateTimeOffset Ends { get; set; }
        }
    
        public partial class TrackingNumberInfo
        {
            [JsonProperty("trackingNumber")]
            public string TrackingNumber { get; set; }
    
            [JsonProperty("trackingNumberUniqueId")]
            public string TrackingNumberUniqueId { get; set; }
    
            [JsonProperty("carrierCode")]
            public string CarrierCode { get; set; }
        }
    
        public partial class TrackyThing
        {
            public static TrackyThing FromJson(string json) => JsonConvert.DeserializeObject<TrackyThing>(json, HackyTracky.Converter.Settings);
        }
    
        public static class Serialize
        {
            public static string ToJson(this TrackyThing self) => JsonConvert.SerializeObject(self, HackyTracky.Converter.Settings);
        }
    
        internal static class Converter
        {
            public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
            {
                MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
                DateParseHandling = DateParseHandling.None,
                Converters =
                {
                    new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
                },
            };
        }
    
        internal class ParseStringConverter : JsonConverter
        {
            public override bool CanConvert(Type t) => t == typeof(long) || t == typeof(long?);
    
            public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
            {
                if (reader.TokenType == JsonToken.Null) return null;
                var value = serializer.Deserialize<string>(reader);
                long l;
                if (Int64.TryParse(value, out l))
                {
                    return l;
                }
                throw new Exception("Cannot unmarshal type long");
            }
    
            public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
            {
                if (untypedValue == null)
                {
                    serializer.Serialize(writer, null);
                    return;
                }
                var value = (long)untypedValue;
                serializer.Serialize(writer, value.ToString());
                return;
            }
    
            public static readonly ParseStringConverter Singleton = new ParseStringConverter();
        }
    }
    

    还有其他服务做同样的事情 - json2csharp 也很受欢迎

    完成此操作后,您可以像在类顶部的注释中所说的那样转换对象:

    var trackyThing = TrackyThing.FromJson(jsonString);
    

    并通过 LINQ 访问内容:

    var allScanEvents = trackyThing.Output.CompleteTrackResults
      .SelectMany(ctr => ctr.TrackResults)
      .SelectMany(tr => tr.ScanEvents);
        
    

    【讨论】:

      猜你喜欢
      • 2019-07-29
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-19
      • 2018-12-10
      • 1970-01-01
      相关资源
      最近更新 更多