【问题标题】:How to ignore JsonPropertyNameAttribute annotation when serialize object?序列化对象时如何忽略 JsonPropertyNameAttribute 注释?
【发布时间】:2020-08-06 23:54:06
【问题描述】:

我想从使用不同命名策略的其他人 API 反序列化 JSON,所以我将 JsonPropertyNameAttribute 添加到 POCO

public class X
{
  [JsonPropertyNameAttribute("uid")]
  public string Name {get;set;}
}

它希望它被序列化为

{
  "name" : xx,
  .....
}

{ 
  "Name" : xx,
  .....
}

不是

{
  "uid" : xx,
  ......
}

如何优雅地使用System.Text.Json
(除了创建新的 POCO 像 X 没有注释)

【问题讨论】:

  • 目前,我最简单的方法是使用 Newtonsoft.Json 对其进行序列化

标签: c# .net .net-core json.net system.text.json


【解决方案1】:

在没有 JsonPropertyNameAttribute 的情况下定义您的模型

public class X
{
    public string Name { get; set; }
}

创建cutsom策略

public class DeserializePolicy : JsonNamingPolicy
{
    public override string ConvertName(string name)
        => name == "Name" ? "uid" : name;
}

用它来反序列化

string text = "{\"uid\":\"abc\"}";

var options = new JsonSerializerOptions { PropertyNamingPolicy = new DeserializePolicy() };

var x = JsonSerializer.Deserialize<X>(text, options);

无策略的序列化

var json = JsonSerializer.Serialize<X>(x);

我不确定这是否可以优雅地考虑。

【讨论】:

  • 谢谢,它很优雅,但是当它发生在很多重命名属性和很多 POCO 中时,似乎冗长。
猜你喜欢
  • 1970-01-01
  • 2018-01-23
  • 2014-05-11
  • 1970-01-01
  • 2016-01-22
  • 2016-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多