Search code examples
c#jsonserializationdeserialization

Deserialization further address of json in c#


I am deserializing a json in c#. but address field needs furher deserialization. help me how to do it

{"Name":"name something", "Start":"2021-11-10T09:00:00", "End":"2021-11-14T09:00:00", "AdditionalInformation":"infoadfasf.", "Address":{"Information":"Cancha Convive "Parque la Hermandad" colonia El Hogar, Tegucigalpa.","City":"Tegucigalpa, Francisco Moraz\u00e1n","CountryIso2":"HN"}}

i cant get the properties of address, eg address have (city, country..)

my c# code

public class Event
{
    public string Name { get; set; }
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
    public string AdditionalInformation { get; set; }
    public Address1 address1 { get; set; }
}

public class Address1
{
    public string Information { get; set; }
    public string City { get; set; }
    public string CountryIso2 { get; set; }
}

data service for deserialization

 public class DataService
{
   
    public async Task<IEnumerable<Event>?> GetEventsAsync()
    {
        return JsonSerializer.Deserialize<IEnumerable<Event>>(await File.ReadAllTextAsync("Data/Events.json"));
    }
}

Solution

    1. The Address field in the JSON is unmatched with the address1 in Event model.

      1.1. Either rename the property to Address

    public class Event
    {
        ...
    
        public Address1 Address { get; set; }
    }
    

    1.2. Or using the JsonProperty attribute:

    [JsonProperty("Address")]
    public Address1 address1 { get; set; }
    

    Would suggest using the approach 1.1 which is declaring the property with Pascal Casing naming, following the C# naming convention.

    1. The provided JSON is an object, but not an array. You should deserialize as Event but not IEnumerable<Event>. Following change requires to change the method signature for GetEventAsync method as well.
    public async Task<Event> GetEventAsync()
    {
        return JsonSerializer.Deserialize<Event>(await File.ReadAllTextAsync("Data/Events.json"));
    }