Problem
When you deserialize JSON with a “trailing comma”, you get the following error:
The JSON object contains a trailing comma at the end which is not supported in this mode. Change the reader options.
JSON properties are separated with commas. A trailing comma is one that has no properties after it. Here’s an example of a trailing comma:
{
"id":123,
"title":"Jurassic Park",
}
Code language: JSON / JSON with Comments (json)
This is technically invalid JSON (according to the official JSON spec), but it’s really not a good reason for deserialization to fail. You can update the serializer to allow trailing commas.
Solution
To allow trailing commas, set the JsonSerializerOptions.AllowTrailingCommas to true, like this:
using System.Text.Json;
var movieJson = "{\"id\":123,\"title\":\"Jurassic Park\",}";
var options = new JsonSerializerOptions()
{
AllowTrailingCommas = true
};
var movie = JsonSerializer.Deserialize<Movie>(movieJson, options);
Code language: C# (cs)
Note: If you’re using ASP.NET Core, read how to change the JSON serialization settings.