Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove $id during JSON serialization

Tags:

json.net

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...

like image 248
Sajid Ali Avatar asked Jul 18 '12 13:07

Sajid Ali


People also ask

What is a JSON serialization exception?

JsonSerializationException(String, Exception) Initializes a new instance of the JsonSerializationException class with a specified error message and a reference to the inner exception that is the cause of this exception.

How does JSON serialization work?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.

Does JSON serialize data?

The json module exposes two methods for serializing Python objects into JSON format. dump() will write Python data to a file-like object. We use this when we want to serialize our Python data to an external JSON file. dumps() will write Python data to a string in JSON format.

Why we serialize a JSON?

The purpose of serializing it into JSON is so that the message will be a format that can be understood and from there, deserialize it into an object type that makes sense for the consumer.


2 Answers

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; 
like image 150
Etienne Desgagné Avatar answered Dec 05 '22 23:12

Etienne Desgagné


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"

like image 38
TylerY86 Avatar answered Dec 05 '22 22:12

TylerY86