Common JSON serialization configuration is as follows:
// JSON serialization configuration
private static readonly JsonSerializerOptions JsonSetting = new JsonSerializerOptions()
{
// First letter lowercase
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
// Formatted output, i.e., automatic line breaks and added spaces
WriteIndented = true,
};
When serializing, use:
JsonSerializer.Serialize(obj, JsonSetting)
Other properties of serialization configuration:
Properties
| AllowTrailingCommas | Gets or sets a value indicating whether to allow (and ignore) extra commas at the end of lists of JSON values within objects or arrays in the JSON payload being deserialized. |
| --------------------------- | --------------------------------------------------------------------------------------------------------- |
| Converters | Gets the list of registered user-defined converters. Can convert numbers to strings, etc.; |
| DefaultBufferSize | Gets or sets the default buffer size (in bytes) to use when creating a temporary buffer. |
| DefaultIgnoreCondition | Specifies a condition to determine when to ignore properties with default values during serialization or deserialization. |
| DictionaryKeyPolicy | Generates lowercase first letters for dictionary keys |
| Encoder | Gets or sets the encoder to use when escaping strings, or null
(to use the default encoder). |
| IgnoreNullValues | Gets or sets a value that determines whether null
values are ignored during serialization. The default value is false
. |
| IgnoreReadOnlyFields | Determines whether to ignore read-only fields during serialization. A field is read-only if it is marked with the readonly
keyword. The default value is false
. |
| IgnoreReadOnlyProperties | Gets a value that determines whether to ignore read-only properties during serialization. The default value is false
. |
| IncludeFields | Determines whether fields are handled during serialization and deserialization. The default value is false
. |
| MaxDepth | Gets or sets the maximum depth allowed when serializing or deserializing JSON; the default value of 0 indicates a maximum depth of 64. |
| NumberHandling | Specifies how numeric types are handled during serialization or deserialization. |
| PropertyNameCaseInsensitive | Gets or sets a value that determines whether property names are compared case-insensitively during deserialization. The default value is false
. |
| PropertyNamingPolicy | Generates JSON with the first letter lowercase. |
| ReadCommentHandling | Defines how comments are handled during the deserialization process. |
| ReferenceHandler | Configures how object references are handled when reading and writing JSON. |
| WriteIndented | Formats the output JSON with automatic line breaks, spaces, and indentation. |
文章评论