Removing $id from JSON returned by WebApi

R

If you’re using the default JSON formatter (ie- haven’t set another one up) your outputted JSON may look something like this:

[
    {
        $id: "1",
        FirstName: "John",
        LastName: "Smith",
    },
    {
        $id: "2",
        FirstName: "Sarah",
        LastName: "Harris",
    },
    {
        $id: "3",
        FirstName: "Michael",
        LastName: "Jones",
    },
    {
        $id: "4",
        FirstName: "Harry",
        LastName: "Green",
    }
]

Notice the $id element appearing.

What you see as $id is actually a reference used to preserve the handle so that if the element repeats somewhere in the output, it wont print a repeat pf the data, it will just set a “$ref” property of the duplicate to the “$id” of the original.

You can disable this by adding the following code to Application_Start method in the Global.asax file:

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;