我似乎无法阻止Newtonsoft.Json.PreserveReferencesHandling.Objects
在序列化对象时使用Web API / JSON.NET 。换句话说,尽管使用以下设置,但始终在序列化对象中使用$ id / $ ref:
public class MvcApplication : System.Web.HttpApplication {
protected void Application_Start () {
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
}
public static class WebApiConfig {
public static void Register (HttpConfiguration config) {
JsonMediaTypeFormatter jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().Single();
jsonFormatter.UseDataContractJsonSerializer = false;
jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
jsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
}
}
有任何想法吗?
如果在对象(例如DataContract)上使用序列化属性,请参阅JSON.Net文档中有关序列化属性的内容:
除了使用内置的Json.NET属性外,Json.NET还将查找[SerializableAttribute] [2](如果DefaultContractResolver上的IgnoreSerializableAttribute设置为false)[DataContractAttribute] [3],[DataMemberAttribute] [4]和[NonSerializedAttribute] [5] ...在确定如何序列化和反序列化JSON时。
它还说:
笔记
Json.NET属性优先于标准.NET序列化属性,例如,如果属性中同时存在JsonPropertyAttribute和DataMemberAttribute并自定义名称,则将使用JsonPropertyAttribute的名称。
看来解决问题的方法是[JsonObject(IsReference = false)]
像这样添加到您的对象中:
[DataContract(IsReference = true)]
[JsonObject(IsReference = false)]
public class MyObject
{
[DataMember]
public int MyProperty { get; set; }
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句