我有下一个结构的DTO:
“body" : "Lorem ipsum Lorem ipsum Lorem ipsum\n\n!
[Conference Centre]
(\/\/images.places.com\/434432\/4234328423rf234\/Conference_Centre.jpg)\n\n\
more of the same"
从服务器我收到下一个型号的json:
public class DTO
{
public int Id {get;set;}
[JsonProperty("Id")]
public int ServerId {get;set;}
}
我想将服务器映射中的json从ServerModel反序列化为DTO,并将规则public class ServerModel
{
public int Id {get;set;}
}
=>
从Id
属性反序列化。但目前我收到错误:
名为' Id'的成员已存在
ServerId
。使用 JsonPropertyAttribute指定另一个名称。
我可以以某种方式解决这个问题吗?或者我只是可以更改我的ServerModel以匹配我在客户端上的内容(DTO
)?
答案 0 :(得分:6)
如果您只是不想将任何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不允许的,因为这样的合同无法序列化。