问题
I am trying to deserialize GeoJSON using the JSON.net library. The geometry component of each feature can be of many different types based on the "type" attribute value.
I need to deserialize the geometry component of this GeoJSON into a geometry object model like so:
public abstract class Geometry { ... }
public class Point : Geometry { ... }
public class LineString : Geometry { ... }
public class Polygon : Geometry { ... }
So based on the value of the "type" attribute, it will deserialize into the corresponding .net concrete type, but accessed via its base Geometry class.
Does the JSON.net library offer anything similar to the KnownTypeAttribute in WCF or XmlElementAttribute in XML Serialization that allows me to deserialize JSON to a base class with a set of known derived classes?
回答1:
Documentation here shows this example:
[JsonObject(MemberSerialization.OptIn)]
public class Person
{
// "John Smith"
[JsonProperty]
public string Name { get; set; }
// "2000-12-15T22:11:03"
[JsonProperty]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime BirthDate { get; set; }
// new Date(976918263055)
[JsonProperty]
[JsonConverter(typeof(JavaScriptDateTimeConverter))]
public DateTime LastModified { get; set; }
// not serialized
public string Department { get; set; }
}
来源:https://stackoverflow.com/questions/6449569/deserializing-json-to-a-net-base-class-with-json-net