Newtonsoft json serializer returns empty object

后端 未结 1 529
长情又很酷
长情又很酷 2020-12-29 12:23

Ok - I\'ve been beating my head against this for a few of hours now. Time to ask for help.

I have just upgraded my Web application project to ASP.NET MVC 4 RC, and t

相关标签:
1条回答
  • 2020-12-29 13:17

    Ok - there have been numerous changes, which result is some pretty radical changes to the Json output. These changes also include how custom TypeConverters are applied.

    I have written a basic resolver which (for us at least) causes the Newtonsoft serializer to behave more like a basic Serializable object serializer - i.e. serializes all PROPERTIES, and doesnt use custom TypeConverters...

    /// <summary>
    /// A resolver that will serialize all properties, and ignore custom TypeConverter attributes.
    /// </summary>
    public class SerializableContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
    {
        protected override IList<Newtonsoft.Json.Serialization.JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var properties = base.CreateProperties(type, memberSerialization);
    
            foreach (var p in properties)
                p.Ignored = false;
    
            return properties;
        }
    
        protected override Newtonsoft.Json.Serialization.JsonContract CreateContract(Type objectType)
        {
            var contract = base.CreateContract(objectType);
    
            if (contract is Newtonsoft.Json.Serialization.JsonStringContract)
                return CreateObjectContract(objectType);
            return contract;
        }
    }
    

    * REGISTRATION * In your MvcApplication "Application_Start"...

    GlobalConfiguration.Configuration.Formatters
        .JsonFormatter.SerializerSettings.ContractResolver = 
            new SerializableContractResolver()
            {
                IgnoreSerializableAttribute = true
            };
    
    0 讨论(0)
提交回复
热议问题