JSON.net null property

二次信任 提交于 2019-12-24 13:30:26

问题


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.

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

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

What am i doing wrong here?


回答1:


The two things that pop in my mind are

  • Change Depth from a property to a method

or

  • Make the entire class opt-in and specify which properties should be serialized

You can read more about that here




回答2:


ObjectCreationHandling = ObjectCreationHandling.Replace solves this.



来源:https://stackoverflow.com/questions/23993871/json-net-null-property

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