I am using Newtonsoft JSON.NET for object serialization in an ASP.NET Core (.NET 8) project implementing REST APIs and I need to change serialization settings used for Swagger examples from serialization settings used elsewehere, but I do not see any methods of customizing serialization settings just for the Swagger UI. Is it possible, and if so, are there any examples?
Here is the background info and some details of what I’m looking for.
We use JSON.NET because it is more forgiving when dealing with data that we do not control. For example, one of the external services we can return error details with embedded non-escaped new lines in the string properties, which goes against the JSON spec. This is not our code, so there is nothing we can do to fix it and Microsoft’s JSON serialization cannot handle it, while JSON.NET can. So, we have to use it for now.
When we configure the MVC settings for JSON, we use the following options:
mvc.AddNewtonsoftJson(
options =>
{
options.SerializerSettings.Converters.Add(new StringEnumConverter());
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
// Do not change the following line or it may fail to serialize hierarchical data.
options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
});
This works fine except that when Swagger UI shows examples of the input objects expected to be passed to the POST/PATCH methods, these objects include the $id
property, which will be confusing for the readers. For example, if I have an object like this one:
public class GroupRequestCreateExample: IExamplesProvider<Group>
{
public Group GetExamples()
{
Group group = new()
{
DisplayName = "Fonzie Fans",
Description = "Everyone who likes Fonzie."
};
return group;
}
}
the Swagger example will show it as:
{
"$id":"1",
"displayName":"Fonzie Fans",
"description": "Everyone who likes Fonzie."
}
and I wan it to look like:
{
"displayName":"Fonzie Fans",
"description": "Everyone who likes Fonzie."
}
I understand how turn displaying the $id
property off globally, but if I do, it breaks the call that receive hierarchical data from external services, so I need to keep the options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects
setting for everything except the Swagger samples.
Is it possible?