I am using NewtonSoft.JSON. When running
JsonConvert.SerializeObject(myObject)
it is adding an
To remove the $id in JSON for my web API. I included [JsonObject(IsReference = false)] for my class objects and [JsonProperty(IsReference = false)] for my properties that are of object types. In my case the RespObj property is generic Type T and could take any object type I pass to it including collections so I had to use [JsonProperty(IsReference = false)] to get rid of the $id in the serialized JSON string.
I did not change my WebApiConfig because I was using the MVC help page for WEB API and it required me to have this configuration in my webApiconfig:
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;
json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
The class object
[DataContract(IsReference = true)]
[JsonObject(IsReference = false)]
public class QMResponse<T> where T : new()
{
public QMResponse()
{
}
/// <summary>
/// The response code
/// </summary>
public string RespCode { get; set; }
/// <summary>
/// The response message
/// </summary>
public string RespMxg { get; set; }
/// <summary>
/// The exception message
/// </summary>
public string exception { get; set; }
/// <summary>
/// The object type returned
/// </summary>
[JsonProperty(IsReference = false)]
public T RespObj { get; set; }
/// <summary>
/// No of records returned
/// </summary>
public long RecordCount { get; set; }
/// <summary>
/// The Session Object
/// </summary>
public string session_id { get; set; }
}
I added this code to my WebApiConfig register method and I got rid of all $id in JSON.
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
You can keep the basic configuration:
Newtonsoft.Json.PreserveReferencesHandling.All;
I used this code format for my methods
public JsonResult<T> Get()
{
return Json(result);
}
It works fine for me.
The custom ContractResolver setting overrides the PreserveReferencesHandling setting.
In your implementation of DefaultContractResolver/IContractResolver, add this;
public override JsonContract ResolveContract(Type type) {
var contract = base.ResolveContract(type);
contract.IsReference = false;
return contract;
}
This behaves similarly to the PreserveReferencesHandling.None setting without a custom ContractResolver
In case 'id' is a property of your class then apply [JsonIgnore] attribute on it. Otherwise probably here is the answer for your question:
http://james.newtonking.com/json/help/index.html?topic=html/PreserveObjectReferences.htm
If for some reason you're using a custom ContractResolver, take a look at this other stack overflow;
Json.Net adding $id to EF objects despite setting PreserveReferencesHandling to "None"