Tony Nilsson
Tony Nilsson

Reputation: 13

C# Looking for help how to deserialize this kind of json

to start off, I am a beginner. I have been searching for something that looks something like this problem without managing to solve the problem. And now I have been stuck with this problem for a while. I am using an API from our local post delivery where we can get information such as deliverytime, address etc in a json link. But in this case the json looks a bit different and I do not know how to work with it.

I would be really happy if someone could explain to me how I can access the data such as deliverdate and address. Right now when I try, it only shows the value is null.

I use json.net for deserializing

Below you can see how it looks like..

private async void button_Click(object sender, RoutedEventArgs e)
{
    string url = "https://api2.postnord.com/rest/shipment/v1/trackandtrace/findByIdentifier.json?id=...";

    HttpClient client = new HttpClient(); 
    string date = await client.GetStringAsync(new Uri(url));
    var jarray = JsonConvert.DeserializeObject<Rootobject>(date);
}

public class Rootobject
{
    public Trackinginformationresponse TrackingInformationResponse { get; set; }
}

public class Trackinginformationresponse
{
    public Shipment[] shipments { get; set; }
}

public class Shipment
{
    public string shipmentId { get; set; }
    public string uri { get; set; }
    public int assessedNumberOfItems { get; set; }
    public DateTime deliveryDate { get; set; }
    public DateTime estimatedTimeOfArrival { get; set; }
    public Service service { get; set; }
    public Consignor consignor { get; set; }
    public Consignee consignee { get; set; }
    public Statustext statusText { get; set; }
    public string status { get; set; }
    public Totalweight totalWeight { get; set; }
    public Totalvolume totalVolume { get; set; }
    public Assessedweight assessedWeight { get; set; }
    public Item[] items { get; set; }
    public Additionalservice[] additionalServices { get; set; }
    public object[] splitStatuses { get; set; }
    public Shipmentreference[] shipmentReferences { get; set; }
}

public class Service
{
    public string code { get; set; }
    public string name { get; set; }
}

public class Consignor
{
    public string name { get; set; }
    public Address address { get; set; }
}

public class Address
{
    public string street1 { get; set; }
    public string city { get; set; }
    public string countryCode { get; set; }
    public string country { get; set; }
    public string postCode { get; set; }
}

public class Consignee
{
    public Address1 address { get; set; }
}

public class Address1
{
    public string city { get; set; }
    public string countryCode { get; set; }
    public string country { get; set; }
    public string postCode { get; set; }
}

public class Statustext
{
    public string header { get; set; }
    public string body { get; set; }
}

public class Totalweight
{
    public string value { get; set; }
    public string unit { get; set; }
}

public class Totalvolume
{
    public string value { get; set; }
    public string unit { get; set; }
}

public class Assessedweight
{
    public string value { get; set; }
    public string unit { get; set; }
}

public class Item
{
    public string itemId { get; set; }
    public DateTime dropOffDate { get; set; }
    public DateTime deliveryDate { get; set; }
    public string typeOfItemActual { get; set; }
    public string typeOfItemActualName { get; set; }
    public string status { get; set; }
    public Statustext1 statusText { get; set; }
    public Statedmeasurement statedMeasurement { get; set; }
    public Assessedmeasurement assessedMeasurement { get; set; }
    public Event[] events { get; set; }
    public Reference[] references { get; set; }
    public object[] itemRefIds { get; set; }
    public object[] freeTexts { get; set; }
}

public class Statustext1
{
    public string header { get; set; }
    public string body { get; set; }
}

public class Statedmeasurement
{
    public Weight weight { get; set; }
    public Length length { get; set; }
    public Height height { get; set; }
    public Width width { get; set; }
    public Volume volume { get; set; }
}

public class Weight
{
    public string value { get; set; }
    public string unit { get; set; }
}

public class Length
{
    public string value { get; set; }
    public string unit { get; set; }
}

public class Height
{
    public string value { get; set; }
    public string unit { get; set; }
}

public class Width
{
    public string value { get; set; }
    public string unit { get; set; }
}

public class Volume
{
    public string value { get; set; }
    public string unit { get; set; }
}

public class Assessedmeasurement
{
    public Weight1 weight { get; set; }
}

public class Weight1
{
    public string value { get; set; }
    public string unit { get; set; }
}

public class Event
{
    public DateTime eventTime { get; set; }
    public string eventCode { get; set; }
    public string status { get; set; }
    public string eventDescription { get; set; }
    public Location location { get; set; }
}

public class Location
{
    public string displayName { get; set; }
    public string name { get; set; }
    public string locationId { get; set; }
    public string countryCode { get; set; }
    public string country { get; set; }
    public string postcode { get; set; }
    public string city { get; set; }
    public string locationType { get; set; }
}

public class Reference
{
    public string value { get; set; }
    public string type { get; set; }
    public string name { get; set; }
}

public class Additionalservice
{
    public string code { get; set; }
    public string name { get; set; }
}

public class Shipmentreference
{
    public string value { get; set; }
    public string type { get; set; }
    public string name { get; set; }
}
{
    "TrackingInformationResponse": {
        "shipments": [{
            "shipmentId": "85319760154SE",
            "uri": "/ntt-service-rest/api/shipment/85319760154SE/0",
            "assessedNumberOfItems": 1,
            "deliveryDate": "2016-03-22T20:35:00",
            "estimatedTimeOfArrival": "2016-03-22T13:41:00",
            "service": {
                "code": "19",
                "name": "MyPack"
            },
            "consignor": {
                "name": "H&M",
                "address": {
                    "street1": "HULTAGATAN 47",
                    "city": "BORÅS",
                    "countryCode": "SWE",
                    "country": "Sweden",
                    "postCode": "50189"
                }
            },
            "consignee": {
                "address": {
                    "city": "UDDEVALLA",
                    "countryCode": "SWE",
                    "country": "Sweden",
                    "postCode": "45133"
                }
            }
        }]
    }
}

Upvotes: 1

Views: 143

Answers (3)

Gerard Sexton
Gerard Sexton

Reputation: 3210

Like the other answers state, JsonConvert.DeserializeObject<>() is the method you need. After that, you just need to traverse the deserialized data structure.

As to why you are getting NULL after you attempt to deserialize, NULL is returned if the deserializtion fails. Typically when the data is in a bad format or character case fails to match. But for the sample JSON you supplied, it deserilized correctly for me using your classes.

Rootobject root = JsonConvert.DeserializeObject<Rootobject>(data);
if (root == null ||
    root.TrackingInformationResponse == null ||
    root.TrackingInformationResponse.shipments == null ||
    root.TrackingInformationResponse.shipments.Length == 0)
{
    throw new Exception();
}
Shipment shipment = root.TrackingInformationResponse.shipments[0];

if (shipment.consignee == null || shipment.consignee.address == null)
{
    throw new Exception();
}

Console.WriteLine("Consignee: {0}", shipment.consignee);
Console.WriteLine("Estimated Time of Arrival: {0}", shipment.estimatedTimeOfArrival);

Upvotes: 0

Dejo
Dejo

Reputation: 2148

You can try with

var jarray = JsonConvert.DeserializeObject<Rootobject>(date, 
  new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-ddTHH:mm:ss" });

Upvotes: 0

Ken Huynh
Ken Huynh

Reputation: 78

Here's an existing post that might help you.

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

Here's some info on Newtonsoft. http://www.newtonsoft.com/json/help/html/deserializeobject.htm

Example of usage:

Newtonsoft.Json.JsonConvert.DeserializeObject()

Upvotes: 2

Related Questions