Deserializing JSON to a .net base class with JSON.net

痞子三分冷 提交于 2019-12-13 16:14:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!