名为"Id"的成员已存在于“模型"上.使用JsonPropertyAttribute指定其他名称

编程入门 行业动态 更新时间:2024-10-25 07:34:41
本文介绍了名为"Id"的成员已存在于“模型"上.使用JsonPropertyAttribute指定其他名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我具有下一个结构的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指定其他名称

本文发布于:2023-10-30 19:00:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1543722.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   成员   名称   quot   Id

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!