Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize nested json objects into c# objects

Tags:

json

c#

I have the following Json response:

{
  "Customers": [
    {
      "Customer": {
        "Address": {
          "City": "Stockholm",
          "PostalCode": "10123"
        },
        "Classifications": [
          "LoyaltyProgram",
          "Returning",
          "VeryImportant"
        ],
        "FirstName": "Peter",
        "LastName": "Centers",
        "Passport": {
          "Expiration": "2019-01-14",
          "Number": "1564931321655"
        },
      },
      "FirstName": "Peter",
      "LastName": "Centers",
      "Reservation": {
        "AdultCount": 2,
        "AssignedSpaceId": "03f59360-8644-4e29-927a-ad85a6514466",
      },
      "RoomNumber": "302"
    },
  ]
}

I have the following classes for every Customer:

public class CustomerDto
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<string> Classifications { get; set; }
    public PassportDto Passport { get; set; }
    public AddressDto Address { get; set; }
}

public class AddressDto
{
    public string City { get; set; }
    public string PostalCode { get; set; }
}

public class PassportDto
{
    public string Expiration { get; set; }
    public string Number { get; set; }
}

from this I use Json.Net and the following code from one of my methods (extract) where customers below is the response:

var jsonCustomers = JObject.Parse(customers)["Customers"].Children().ToList();
IList<CustomerDto> customerList = new List<CustomerDto>();
foreach (var item in jsonCustomers) {
    customerList.Add(item.ToObject<CustomerDto>());
}

All the values in CustomerDto are filled except for Address and Passport, that are null, and I can't figure out why.

like image 301
Peter Centellini Avatar asked Oct 04 '17 09:10

Peter Centellini


People also ask

How do I deserialize a JSON object?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is JsonProperty C#?

This sample uses JsonPropertyAttribute to change the names of properties when they are serialized to JSON. Types. public class Videogame { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("release_date")] public DateTime ReleaseDate { get; set; } }

What is JsonConvert?

Provides methods for converting between . NET types and JSON types.


1 Answers

Add two new classes:

public class CustomersWrapper
{
    public IEnumerable<CustomerWrapper> Customers { get; set; }
}

public class CustomerWrapper
{
    public CustomerDto Customer { get; set; }
}

and then replace all of your existing code with:

        var results = JsonConvert.DeserializeObject<CustomersWrapper>(input);
        var customerList = results.Customers.Select(z => z.Customer).ToList();

This will ensure that standard deserialisation occurs for all objects in the hierarchy.

This is needed due to the odd structure of your JSON. https://stackoverflow.com/a/45384366/34092 is the same basic issue (and may be worth a read) - essentially you shouldn't really have Customers and Customer in your JSON. Without those, you wouldn't need the two wrapper classes I have specified.

You may also wish to avoid specifying FirstName and LastName twice (unnecessarily) in the JSON.

like image 60
mjwills Avatar answered Sep 30 '22 04:09

mjwills