Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon 使用所需属性和mvvmcross中的jsonrequiredattribute之间有什么区别


使用所需属性和mvvmcross中的jsonrequiredattribute之间有什么区别


在MVVMCROSS中,在处理数据验证和序列化时,通常会发挥两个属性:`ruilt oquiress''和`jsonrequiredAttribute'。这些属性具有不同的目的,并在应用程序生命周期的不同阶段使用。

###必需属性

“必需”属性是`system.com.ponentmodel.dataannotations'名称空间的一部分,用于模型验证。它表明财产必须具有值;否则,该模型被认为是无效的。在模型验证阶段,通常使用此属性后使用此属性。例如,在ASP.NET核心中,如果属性用``必需的]''装饰,则``ModelState`''如果丢失该属性或在模型绑定过程中无效,则将无效。

在MVVMCROSS中,虽然“必需”属性可用于验证,但它不会直接与JSON序列化或次要化过程相互作用。相反,更多的是在进行业务逻辑之前确保填充某些属性。

jsonrequiredAttribute

“ JSONREQUIREDATTRIBUTE”特定于JSON序列化和避免化。它用于表明在避难化过程中必须存在属性。使用JSON数据时,此属性至关重要,因为它可以确保始终存在所需的属性,从而防止由于缺少数据而导致潜在错误。

在MVVMCROSS中,当使用JSON进行导航或在视图模型之间进行数据传输时,`jsonrequiredAttribute`可确保所需的属性被序列化并正确化。这尤其重要,因为MVVMCROSS在很大程度上依赖JSON在导航过程中传递的复杂参数。

###密钥差异

1。目的:
- “必需”是用于通用模型验证的,确保在避免后填充属性。
- `jsonRequiredAttribute`专门用于确保在JSON避难所中存在属性。

2。使用阶段:
- 在验证后,在模型验证期间使用`必要的'。
- `jsonrequiredAttribute`在JSON避免序列化本身时使用。

3。范围:
- `必需的'可以在各种数据格式和验证方案中使用。
- `jsonRequiredAttribute`专门针对JSON数据处理量身定制。

4。行为:
- 如果丢失了标有“必需”的属性,则将导致验证后的验证错误。
- 如果在JSON避难所中丢失了标有“ JSONREQUIRIEDATTRIBUTE”的属性,则通常会抛出异常或导致反序列错误。

总而言之,尽管两个属性都用于确保数据完整性,但“必需”更多地是关于通用模型验证的,而`jsonRequiredAttribute`专门侧重于确保MVVMCross应用程序中JSON序列化和避免过程中的数据存在。

引用:
[1] https://github.com/mvvmcross/nplus1daysofmvvmcross/blob/master/n-crosslight-touch-touch/crosslighttouch/crosslighttouch/properties/annotiations.cs
[2] https://www.mvvmcross.com/documentation/plugins/json
[3] https://stackoverflow.com/questions/49237767/ using-required-and-required-and-jsonrequired-in-asp-net-core-core-model-model-core-model-with-json-body
[4] https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/generators/observableproperty
[5] https://www.mvvmcross.com/documentation/getting-started/mvvmcross-overview
[6] https://www.strathweb.com/2017/12/required-and-and-bindrequired-in-in-asp-net-core-mvc/
[7] https://www.mvvmcross.com/documentation/platform/android/android-view-presenter
[8] https://www.mvvmcross.com/documentation/fundamentals/navigation
[9] https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonrequiredattribute?view=net-9.0
[10] https://www.mvvmcross.com/documentation/fundamentals/viewmodel-lifecycle
[11] https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view= aspnetcore-9.0