简体   繁体   中英

C# Json extract a list of values from a Json list or array

I want to extract the values from "scanEvents" list or array. Each scanEvent has a date, eventtype, eventdescrption, derivedstatus, etc...

I have used several methods, such as this one below, but so far I am unable to extract the values for each "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;
            }

I want to end up with this kind of output below:

 "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"
                        

How do you extract the values (date, eventDescription, derivedstatus) for each event in "scanEvents" list below? This one seems to be buried under several types or objects.

{
    "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": {}
                    }
                ]
            }
        ]
    }
}

you can try something like this

var jsonObject = JObject.Parse(strFedExJSON); 

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

output

  {
    "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"
  }
]

I can make it in one line if you need, but it would be harder to read.

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");
        }
    }
}

output

{"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"}

So, as others have commented (and my feelings align) whenever we have a reasonably amount of processing to do with some JSON thing, it's easier to parse the JSON to objects and work with the objects. I (personally, no affiliation) head over to https://quicktype.io and paste the JSON in there, to generate a set of classes:

// <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();
    }
}

There are other services that do the same thing - json2csharp is popular too

After you've done this, you can just convert your objects like it says in the comment at the top of the classes:

var trackyThing = TrackyThing.FromJson(jsonString);

And access things via LINQ:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM