【问题标题】:Deserializing JSON to a .net base class with JSON.net使用 JSON.net 将 JSON 反序列化为 .net 基类
【发布时间】:2011-06-23 05:06:21
【问题描述】:

我正在尝试使用 JSON.net 库反序列化 GeoJSON。根据“type”属性值,每个要素的几何组件可以有多种不同的类型。

我需要将此 GeoJSON 的几何组件反序列化为几何对象模型,如下所示:

public abstract class Geometry { ... }

public class Point : Geometry { ... }

public class LineString : Geometry { ... }

public class Polygon : Geometry { ... }

因此,根据“type”属性的值,它将反序列化为相应的 .net 具体类型,但通过其基础 Geometry 类访问。

JSON.net 库是否提供类似于 WCF 中的 KnownTypeAttribute 或 XML 序列化中的 XmlElementAttribute 的功能,允许我将 JSON 反序列化为具有一组已知派生类的基类?

【问题讨论】:

    标签: json serialization polymorphism json.net


    【解决方案1】:

    文档here 显示了这个例子:

        [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; }
        }
    

    【讨论】:

    • 这都是关于我发现的 JsonConverter 的。
    猜你喜欢
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 2011-02-02
    相关资源
    最近更新 更多