JSON.net null属性

时间:2014-06-02 11:51:09

标签: c# json.net

我最近解决了这个错误: Type is an interface or abstract class and cannot be instantiated, 使用此处建议的解决方案: Using Json.NET converters to deserialize properties

不幸的是,我遇到了新的问题。在下面的代码中,深度作为反序列化的一部分被调用,反过来调用Prof属性失败,因为' this.Profile'一片空白。 (' this.Profile'是继承自Section类的属性。)

public class TimberSection : Section, IPurlinShape, IEavesBeamShape
    {
        private Profiles.Flat Prof
        {
            get
            {
                var prof = this.Profile as Profiles.Flat;
                if (prof != null)
                    return prof;
                else
                    throw new DataMissingException("Expected Rectangle profile");
            }
        }

        public override double Depth { get { return Prof.Depth; } }
}

我使用http://www.jsoneditoronline.org/来查看我的对象,似乎一切都是正确的。在反序列化时出现null的profile对象具有与序列化之前的对象相同的值。

下面是我的序列化方法,然后立即对其进行反序列化。

        string serialisedEnquiry = JsonConvert.SerializeObject(enquiry, Formatting.Indented, new JsonSerializerSettings
         {
             TypeNameHandling = TypeNameHandling.Objects,
             TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
         });

        Enquiry enq = JsonConvert.DeserializeObject<Enquiry>(serialisedEnquiry, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Objects
        });

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

我想到的两件事是

  • Depth从属性更改为方法

  • 制作整个班级opt-in并指定应序列化哪些属性

您可以详细了解here

答案 1 :(得分:0)

ObjectCreationHandling = ObjectCreationHandling.Replace解决了这个问题。