我具有下一个结构的DTO:
I have DTO with next structure :
public class DTO { public int Id {get;set;} [JsonProperty("Id")] public int ServerId {get;set;} }从服务器上,我从下一个模型接收json:
From server I receive json from next model :
public class ServerModel { public int Id {get;set;} }我想使用规则 => Id 从服务器映射到 ServerId 属性将json从ServerModel反序列化为DTO.但是目前我得到了错误:
I want to Deserialize json from ServerModel into DTO with rule => Id from server map to ServerId property. But currently I get error :
DTO 上已经存在一个名称为"Id"的成员.使用JsonPropertyAttribute指定另一个名称.
A member with the name 'Id' already exists on DTO. Use the JsonPropertyAttribute to specify another name.
我能以某种方式解决此问题吗?或者我只是可以更改我的ServerModel使其与客户端( DTO )上的内容匹配?
Can I somehow resolve this? Or I just can change my ServerModel to match what I have on client (DTO) ?
推荐答案如果您只是不想将任何JSON值读取到 DTO.Id 中,则应应用 [JsonIgnore]
If you simply don't want to read any JSON values into DTO.Id, you should apply [JsonIgnore] to it:
public class DTO { [JsonIgnore] public int Id {get;set;} [JsonProperty("Id")] public int ServerId {get;set;} }已这样做,在反序列化以下JSON后: {"Id":101} , DTO.ServerId 将获得 101 ,而不会设置 DTO.Id .
Having done so, upon deserializing the following JSON: {"Id" : 101}, DTO.ServerId will get the value of 101 while DTO.Id will not be set.
您正在指定一个JSON数据协定,该协定将两个不同的c#属性映射到名为"Id" 的JSON属性.Json.NET不允许这样做,因为这样的合同无法序列化.
As it is you're specifying a JSON data contract that maps two different c# properties to a JSON property named "Id". This is not allowed by Json.NET, since such a contract could not be serialized.
更多推荐
名为"Id"的成员已存在于“模型"上.使用JsonPropertyAttribute指定其他名称
发布评论