名称为 'Id' 的成员已存在于“模型”上。使用 JsonPropertyAttribute 指定另一个名称

A member with the name 'Id' already exists on `Model`. Use the JsonPropertyAttribute to specify another name

我有下一个结构的 DTO :

public class DTO
{
   public int Id {get;set;}
   [JsonProperty("Id")]
   public int ServerId {get;set;}
}

我从服务器收到来自下一个模型的 json:

public class ServerModel
{
   public int Id {get;set;}
}

我想使用规则 => Id 从服务器映射到 ServerId 属性 将 json 从 ServerModel 反序列化为 DTO。但目前我收到错误:

A member with the name 'Id' already exists on DTO. Use the JsonPropertyAttribute to specify another name.

我能以某种方式解决这个问题吗?或者我可以更改我的 ServerModel 以匹配客户端上的内容 (DTO) ?

如果您只是不想将任何 JSON 值读入 DTO.Id,您应该对其应用 [JsonIgnore]

public class DTO
{
   [JsonIgnore]
   public int Id {get;set;}
   [JsonProperty("Id")]
   public int ServerId {get;set;}
}

这样做后,在反序列化以下 JSON 时:{"Id" : 101}DTO.ServerId 将获得 101 的值,而 DTO.Id 将不会被设置.

您正在指定一个 JSON 数据协定,它将两个不同的 c# 属性映射到一个名为 "Id" 的 JSON 属性。 Json.NET 不允许这样做,因为这样的合同无法序列化。