Background and motivation
Kotlin / Gson supports an alternate name for json properties, which can be convenient to allow deserializing similar json to a unified class object.
Currently, JsonPropertyNameAttribute does not have support for this, and it is not possible to specify multiple instances of JsonPropertyNameAttribute.
Having this would remove the need for writing a custom JsonConverter for this case.
Note: this is only about deserialization - serialization will always use the default name value.
API Proposal
namespace System.Text.Json.Serialization
{
/// <summary>
/// Specifies the property name that is present in the JSON when serializing and deserializing.
/// This overrides any naming policy specified by <see cref="JsonNamingPolicy"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class JsonPropertyNameAttribute : JsonAttribute
{
/// <summary>
/// Initializes a new instance of <see cref="JsonPropertyNameAttribute"/> with the specified property name.
/// </summary>
/// <param name="name">The name of the property.</param>
public JsonPropertyNameAttribute(string name)
{
Name = name;
}
/// <summary>
/// Initializes a new instance of <see cref="JsonPropertyNameAttribute"/> with the specified property name
/// and alternative property names for deserialization.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="alternatives">The alternative names of the property.</param>
public JsonPropertyNameAttribute(string name, string[] alternatives)
{
Name = name;
Alternatives = alternative;
}
/// <summary>
/// The name of the property.
/// </summary>
public string Name { get; }
/// <summary>
/// The alternative names of the property.
/// </summary>
/// <remarks>
/// Is only used for deserialization
/// </remarks>
public string[] Alternatives { get; }
}
}
API Usage
public class Test
{
[JsonPropertyName("property", alternatives = { "oldPropertyNameForBackwardsCompatibility" })]
public string Property { get; set; }
}
Alternative Designs
No response
Risks
While I would say having a clean json response from an API would be better, one does not always have control over the responses of the API.
Background and motivation
Kotlin / Gson supports an
alternatename for json properties, which can be convenient to allow deserializing similar json to a unified class object.Currently,
JsonPropertyNameAttributedoes not have support for this, and it is not possible to specify multiple instances ofJsonPropertyNameAttribute.Having this would remove the need for writing a custom JsonConverter for this case.
Note: this is only about deserialization - serialization will always use the default
namevalue.API Proposal
API Usage
Alternative Designs
No response
Risks
While I would say having a clean json response from an API would be better, one does not always have control over the responses of the API.