Newtonsoft 忽略属性?

时间:2023-04-24
本文介绍了Newtonsoft 忽略属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我目前正在使用相同的 C# DTO 通过 LoveSeat 从 CouchDB 中提取数据,我将通过 ASP MVC 控制器返回 JSON.

I am currently using the same C# DTOs to pull data out of CouchDB, via LoveSeat which I am going to return JSON via an ASP MVC controller.

我正在使用 NewtonSoft 库对我的 DTO 进行序列化,然后再通过控制器发送它们.

I am using the NewtonSoft library to seralise my DTOs before sending them down through the controller.

但是,由于 CouchDB 也使用 NewtonSoft,因此它也尊重属性级别的 NewtonSoft 属性,例如

However, as CouchDB also uses NewtonSoft it is also respecting the property level NewtonSoft attributes such as

[JsonIgnore]
[JsonProperty("foo")]

有没有办法告诉 newtonsoft 库明确地忽略这些属性?LoveSeat 允许我提供自己的 IObjectSerializer 实现,这使我可以完全控制 netwonsofts JsonSerializerSettings.那么,我可以通过使用这些设置来忽略这些属性吗?

Is there anyway to tell the newtonsoft library to ignore these attributes explicitly? LoveSeat allows me to provide my own implementation of IObjectSerializer, which gives me full control over netwonsofts JsonSerializerSettings. So, can I ignore the attributes by using those settings ?

我现在看到的唯一选择是欺骗我的 DTO.虽然这并不可怕,但也不是很好.

I ask as the only alternative I can see at this point, is to dupe my DTOs. While not that's not terrible, it isn't great either.

我能看到的唯一另一种方法是将我自己版本的 Newtonsoft.Json 源代码引入我的项目中,使用不同的程序集名称等.但是这种方式肯定是疯狂的,我只会在我之前欺骗 DTO沿着这条路走.

The only other way I can see is to bring in my own version of the Newtonsoft.Json source into my project, with a different assembly name etc etc. But this way madness definitely lies and I will just dupe the DTOs before I go down this road.

推荐答案

我最终制作了我需要的所有属性,只需将属性添加到虚拟,并在另一个类中单独覆盖它们,并使用相关的 newtonsoft 属性.

I ended up making all properties I needed to only add attributes to virtual, and overriding them alone in another class, with the relevant newtonsoft attributes.

这允许我在从 CouchDB 反序列化并为 GET 序列化时有不同的序列化行为,而不会受到太多欺骗.两者结合很好,而且是一个奖励.无论如何我都想要对基础进行任何更改.

This allows me to have different serialisation behavior when de-serialising from CouchDB and serialising for a GET, without too much dupe. It is fine, and a bonus, that the two are coupled; any changes in the base i would want anyway.

很高兴知道我最初的问题是否可行?

It would still be nice to know if my original question is possible?

这篇关于Newtonsoft 忽略属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Metro 应用程序中的 FTP 下一篇:如何创建 JSON.NET 日期到字符串自定义转换器

相关文章