I can't seem to prevent Web API/JSON.NET from using Newtonsoft.Json.PreserveReferencesHandling.Objects
when serializing objects. In other words, $id/$ref are always used in the serialized objects despite using the following settings:
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;
}
}
Any ideas?
Put this in the Global.asax to configure reference handling. PreserveReferencesHandling should not be 'All'
[JsonIgnore]
worked for me. Within the model, include:Unfortunately, this must be done for each case where needed.
My application was causing error i debugged my asp.net application till it gave me the collection of model causing this issue. just placed the [JsonIgnore] tag and it worked fine.
You can manually test by assigning [JsonIgnore] to all ICollection in Model to discover the source of issue.
If using serialization attributes on your objects (such as DataContract), from the JSON.Net documentation on Serialization Attributes:
It also says this:
It seems the solution to the problem is to add
[JsonObject(IsReference = false)]
to your object(s) like this:Here is some javascript I'm using to handle the $id/$ref objects on the client side: