mercredi 14 février 2018

Include Class name as part of the serialization in JSON C#

I have a specific situation where I need to include the class name as property in JSON when classes are serialized.

I have decorated my class with a custom attribute as below:

 [OntologyArea("con", " http://someurl/area/DomicileAddress")]
    public class DomicileAddress : IContactPoint
    {

        [JsonProperty(PropertyName = "con:hasAddressPoint")]
        public IAddressPoint AddressPoint
        {
            get; set;
        }
    }

In the above example the OntologyArea attribute should be read and included as a Property. The propery name should be the first argument of OntologyArea + the class name (i.e con:DomicileAddress) and the value should be the concrete class of IAddressPoint.

The tricky part is that the concrete class of IAddressPoint might need to do the same as shown here:

[OntologyArea("geo", "http://someurl.net/geolocation")]
    public class StreetAddress : IAddressPoint
    {
        [JsonProperty("geo:hasStartingStreetNumber")]
        public string StartingStreetNumber
        {
            get; set;
        }
    }

an example of JSON:

"con:DomicileAddress" : {
    "con:hasAddressPoint" : {
        "geo:StreetAddress" : {
            "geo:hasEndingStreetNumber" : ""
        }
    }
}

So if any object does have a OntologyArea attribute I need to add a parent level. If it does not contain this attribute normal serilization should continue.

Please let me know If I need to explain more.





Aucun commentaire:

Enregistrer un commentaire