Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

250
Visualizações
Is there a way to have JSON.net honor the System.Text.Json JsonPropertyName attribute

I have a C# type that represents a deserialized C# payload. But it's deserialized in one place by System.Text.Json. In another place, it's Json.NET.

So right now, I have to attribute the properties using both [JsonProperty] (for JSON.NET) and [JsonPropertyName] (for System.Text.Json).

Is there a way to tell JSON.NET recognize the JsonPropertyName attribute so I don't have to annotate each property twice?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can create custom contract resolver which will search for JsonPropertyName attribute and use value from it. Example one can look something like that:

public class ContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);

        if (member.GetCustomAttribute<JsonPropertyNameAttribute>() is {} stj)
        {
            property.PropertyName = stj.Name;
            return property;
        }

        return property;
    }
}

And usage:

class MyClass
{
    [JsonProperty("P1")]
    public int MyProperty { get; set; }
    [JsonPropertyName("P2")]
    public int MyProperty2 { get; set; }
}

var settings = new JsonSerializerSettings
{
    ContractResolver = new ContractResolver()
};  

Console.WriteLine(JsonConvert.SerializeObject(new MyClass(), settings)); // prints {"P1":0,"P2":0}
Console.WriteLine(JsonConvert.DeserializeObject<MyClass>("{'P1':1,'P2':2}", settings).MyProperty2); // prints 2
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda