JSON.net空属性 [英] JSON.net null property

查看:72
本文介绍了JSON.net空属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近解决了此错误: Type is an interface or abstract class and cannot be instantiated, 通过使用此处建议的解决方案: 使用Json.NET转换器对属性进行反序列化.

I recently solved this error: Type is an interface or abstract class and cannot be instantiated, by using the solution suggested here: Using Json.NET converters to deserialize properties.

不幸的是,我对此有了新的问题.在下面的代码中,深度将作为反序列化的一部分被调用,而反序列化又调用了Prof属性,因为"this.Profile"为空,因此该属性失败. ("this.Profile"是从Section类继承的属性.)

Unfortunately I am getting new issues with this. In the code below, Depth gets called as part of the deserialisation, which in turn calls the Prof property which fails because 'this.Profile' is null. ('this.Profile' is a property inherited from the Section class.)

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的配置文件对象的值与序列化之前的对象相同.

I used http://www.jsoneditoronline.org/ to view my object and it seems everything is correct. The profile object that is coming up null when i deserialise, has a value the same as the object prior to serialization.

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

Below is my method for serialising it, then deserialising it immediately after.

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

我在这里做错什么了?

推荐答案

ObjectCreationHandling = ObjectCreationHandling.Replace解决了此问题.

ObjectCreationHandling = ObjectCreationHandling.Replace solves this.

这篇关于JSON.net空属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆