如何使用自定义属性指定属性子集以序列化?
C# 我有一个大型的属性。有时我想一起更新的属性组不同,但不想在请求中发送整个对象。
是否有一种简单的方法可以使用Jsonserializer,并且仅选择具有特定属性的序列化属性?
我想执行诸如jsonserializer.serialize(myClass,[customNeaTeAttribute])之类的事情,在其中它只会拔出userfirstname和userLastName。最好是我可以指定要提取的属性列表的地方。
public class MyClass{
[CustomNameAttribute]
public string UserFirstName {get;set;}
[CustomNameAttribute]
public string UserLastName {get;set;}
[CustomAddressAttribute]
public string UserAddressLine1 {get;set;}
[CustomAddressAttribute]
public string UserAddressLine2 {get;set;}
...
}
C#
I have a large class with many properties. There are different groups of properties that I sometimes want to update together, but do not want to send the entire object in a request.
Is there an easy way to use JsonSerializer and have it only select properties for serialization with specific attributes?
I would like to do something like JsonSerializer.Serialize(myclass, [CustomNameAttribute]) where it would only pull out UserFirstName and UserLastName. And preferably where I could specify a list of attributes to extract.
public class MyClass{
[CustomNameAttribute]
public string UserFirstName {get;set;}
[CustomNameAttribute]
public string UserLastName {get;set;}
[CustomAddressAttribute]
public string UserAddressLine1 {get;set;}
[CustomAddressAttribute]
public string UserAddressLine2 {get;set;}
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我首选的解决方案是使用专用的DTO,而不是依赖序列化器。
使用不同的专用DTO时,更容易确保不需要的数据不会泄漏,因为为其编写单元测试更容易。当您依靠JSON Serialiser时,您的测试需要包括完整的ASP.NET堆栈,以便您可以检查JSON。
使用专业DTO的另一个好处是,自然可以更轻松地进行重构和优化。如果您更早知道(更接近数据源),则更容易分析代码,即给定路径只需要特定字段。
即使您想在最后一个可能的点纤细,我认为专门的DTO也是如此。这是走这条路的众多方法之一:
yyou还可以使您的类支持多个接口并序列化界面,但是:
My preferred solution is to use dedicated DTOs rather than depend on the serializer.
When using different specialized DTOs it is easier to ensure that unwanted data doesn't leak out, because it's easier to write a unit test for it. When you depend on json serialiser your test needs to include your full asp.net stack so that you can inspect the json.
Another benefit of using specialised DTOs is that naturally allows easier refactoring and optimising. It is easier to analyse the code if you know earlier (closer to the data source) that only specific fields are needed for a given path.
Even if you want to slim the objects at the last possible point I think a dedicated DTO can be the way to go. Here is one of many ways to go this path:
Yyou could also make your class support multiple interfaces and serialise the interface(s), but: