Creating C# class from Json

Actually, this is not that hard when you use the JsonProperty attribute

public class Class1    {
        [JsonProperty("icao")]
        public string Icao { get; set; } 

        [JsonProperty("iata")]
        public string Iata { get; set; } 

        [JsonProperty("name")]
        public string Name { get; set; } 

        [JsonProperty("city")]
        public string City { get; set; } 

        [JsonProperty("state")]
        public string State { get; set; } 

        [JsonProperty("country")]
        public string Country { get; set; } 

        [JsonProperty("elevation")]
        public int Elevation { get; set; } 

        [JsonProperty("lat")]
        public double Latitude { get; set; } 

        [JsonProperty("lon")]
        public double Longtitude { get; set; } 

        [JsonProperty("tz")]
        public string Tz { get; set; } 
    }

    

    public class Root    {
        [JsonProperty("00AK")]
        public Class1 GeoDatAK{ get; set; } 

        [JsonProperty("00AL")]
        public Class1 GeoDatAL { get; set; } 
    }

to instantiate it do:

Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 

I personally use the properties to shorten the Json send between services and mobile applications. this becomes especially important when using obfuscation as obfuscated classes that are not public should get renamed.

Look at [JsonConstructor] annotation for internal constructors and use parameters named with the properties

in your class this would be:

[JsonConstructor]
internal Class1(string icao)
{
    this.Icao=icao;
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top