英文:
CustomConverter to compare to a property on the same class in web api
问题
我一直在编写一些自定义转换器,扩展了Newtonsoft的JsonConverter,并遇到了一个小问题。假设我在一个类上有两个属性,但它们不能是相同的值。是否可以在转换器中找到另一个属性的值...例如,假设我有一个如下的模型。
我想要能够在CustomCompareConverter中检查Surname的值,以确保它与Firstname的值不相同。
public class Person
{
[JsonConverter(typeof(CustomCompareConverter), "Surname")]
public string Firstname { get; set; }
public string Surname { get; set; }
}
英文:
I've been writing a few customconverters, extending Newtonsofts JsonConverter and stumbled on a little problem. Say I have two properties on a class, but they cannot be the same value. Is it possible to find the value of another property in a converter... for example, say I have a model like so.
I'd want to be able to check the value of Surname in CustomCompareConverter to ensure its not the same value as Firstname
public class Person
{
[JsonConverter(typeof(CustomCompareConverter), "Surname")]
public string Firstname { get; set; }
public string Surname { get; set; }
}
```
</details>
# 答案1
**得分**: 1
以下是翻译好的部分:
"你试图在 JSON 反序列化过程中执行多个应该分开的操作:
1. 将一些外部 JSON 转换为你的领域对象
2. 验证领域对象。
姓氏与名字不能匹配是你的领域的业务规则。因此,将其保留在你的领域内。你可以:
1. 编写一个单独的验证器类,检查你的人员对象的状态并返回一系列验证失败。
2. 在你的 Person 类上实现 `IValidatableObject`,并实现该接口。
3. 像这个 [SO 问题][1] 中的示例一样编写一个自定义验证器。
将 JSON 反序列化过程用作防腐层,以保持外部系统的细节不进入你的领域结构。一旦你将外部对象转换为你的领域对象,然后使用传统方式来验证你的领域对象。"
[1]: https://stackoverflow.com/questions/41900485/custom-validation-attributes-comparing-two-properties-in-the-same-model
<details>
<summary>英文:</summary>
You are trying to do multiple things with the json deserialization process that really should be separated
1. converting some external json into your domain object
2. validating the domain object.
The fact that the Surname cannot match the FirstName property is a business rule of your domain. So keep that within your domain. You can:
1. write a separate validator class that will check the state of your
person object and return a list of validation failures
2. implement ```IValidatableObject``` on your Person class and implement the
interface
3. write a custom validator like in this [SO question][1]
Use the JSON deserialization process as an anti-corruption layer to keep the details of external systems out of your your domain structure. Once you've take the extenal object and converted it to your domain object then use conventional means to validate that your domain object.
[1]: https://stackoverflow.com/questions/41900485/custom-validation-attributes-comparing-two-properties-in-the-same-model
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论