39

I am using NewtonSoft.JSON. When running

JsonConvert.SerializeObject(myObject)

it is adding an $id value to my JSON - like this:

  "$id": "1",
  "BookingId": 0,
  "CompanyId": 0,
  "IsCashBooking": false,
  "PaymentMethod": 0,
  "IsReferral": false,
  "IsReferralPercent": false,
  "ReferralPaymentType": 0,
  "ReferralDues": 0,
  "PassengerId": 0,
  "DepartmentID": 0,
  "CostCenterID": 0,
  "DeadMiles": 0

Can we remove this $id with some JsonSerializerSettings or by any other method?

If yes - then how...

Frederik Struck-Schøning
  • 12,981
  • 8
  • 59
  • 68
Sajid Ali
  • 719
  • 2
  • 7
  • 21

6 Answers6

56

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;
Frederik Struck-Schøning
  • 12,981
  • 8
  • 59
  • 68
Etienne Desgagné
  • 3,102
  • 1
  • 29
  • 36
  • 13
    Valid answer if you don't need recursive serialization (serializing a hierarchy). $id is used to preserve the handle so if the element repeats somewhere it wont repeat the data it will just set $ref property of the duplicate to the $id of the original. In that case this property must be set to Newtonsoft.Json.PreserveReferencesHandling.Objects and Sajid's answer could be used. – parliament Jul 29 '13 at 01:31
  • 2
    I have deleted my post. I am adding my answer here as a comment. So, it can used as a reference to "parliament" suggestion. delete myObject.$id; and that's it. – Sajid Ali Aug 29 '14 at 13:45
9

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"

Community
  • 1
  • 1
TylerY86
  • 3,737
  • 16
  • 29
  • This is the only correct answer for me. It solved the problem in two situations: using a SQL server provider as well as the Oracle ODP provider. – Howie Feb 09 '14 at 10:48
6

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

}
Frederik Struck-Schøning
  • 12,981
  • 8
  • 59
  • 68
Babatola Awe
  • 71
  • 1
  • 4
2

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

Alex Edelstein
  • 518
  • 5
  • 19
peterfoldi
  • 7,451
  • 5
  • 21
  • 19
  • 1
    What about *forcing* NewtonSoft to use either the `id` property value *of* the object *as* the `$id` field, or instead simply use the `id` property for reference handling? This seems like the most logical use, as allowing the serializer to generate it results in different `id`s depending on the total number of graph objects being serialized. (This is a problem if you a serializing objects individually which then need to be assembled into a single object and deserialized) – JoeBrockhaus Mar 31 '15 at 21:58
  • 1
    @JoeBrockhaus Info on achieving that here: http://stackoverflow.com/questions/9237939/how-to-use-custom-reference-resolving-with-json-net – Ada Richards Mar 30 '16 at 16:09
2

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.

Frederik Struck-Schøning
  • 12,981
  • 8
  • 59
  • 68
anicetkeric
  • 321
  • 2
  • 6
1

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

Frederik Struck-Schøning
  • 12,981
  • 8
  • 59
  • 68
om471987
  • 5,398
  • 5
  • 32
  • 40