Search code examples
json.net-core

Removing $id from json file


I have response from Json and it included the $id, is there a way to remove the schema stuff from the response:

Using .Net Core for this API.

{
  "$id": "1",
  "id": "d84935e9-e670-4bb7-99b2-603cda508701",

Thanks in advance


Solution

  • With limited knowledge of your project, I think the $id part might be coming from the default Json behavior.

    Can you check your service configuration where you're registering services? If you have something like

    services.AddControllers()
        .AddJsonOptions(opts =>
        {
            // This generates the $id field to handle circular reference problems
            opts.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve;
        });
    

    or if you're using Newtonsoft.Json

    services.AddControllers()
        .AddNewtonsoftJson(opts => 
        {
            opts.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        });
    

    A circular reference occurs when objects in a model refer back to each other, forming a loop.

    You can choose to ignore circular references, which will prevent the creation of $id fields. When a loop is detected, the serializer will assign null to the object that caused the loop.

    To do this, you can configure it like this in System.Text.Json,

    services.AddControllers()
        .AddJsonOptions(opts =>
        {
            opts.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;
        });
    

    or in Newtonsoft.Json

    services.AddControllers()
        .AddNewtonsoftJson(options =>
        {
            options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        });
    

    hope it helps,