重命名 JsonSerializer 中的字段

发布于 2024-08-14 14:30:09 字数 404 浏览 3 评论 0原文

我有一个类库,需要通过 ASP.NET MVC 框架中的 JsonResult 输出。 (JsonResult 使用 JsonSerializer 生成其输出。)

通过阅读文档,我发现如果将 [ScriptIgnore] 放在公共属性/字段上,它将不会被序列化,就像 [ XML 序列化程序的 XmlIgnore]

我需要 [XmlElement("elementname")] 的等效功能,它绝对指定输出序列化中的字段/属性的名称。我有一个名为 Elements 的字段,需要将其序列化为名为 elements 的字段。

如何使用默认的 JsonSerializer 来完成此任务?

谢谢, 大卫

I have a class library that I need to output via a JsonResult in the ASP.NET MVC framework. (JsonResult uses the JsonSerializer to produce its output.)

I discovered through reading the documentation that if you put [ScriptIgnore] on a public property/field, it will not get serialized, much like [XmlIgnore] for the XML serializer.

I need the equivalent functionality of [XmlElement("elementname")], which specifies absolutely the name of the field/property in the output serialization. I have a field called Elements that needs to get serialized to a field named elements.

How can I accomplish this using the default JsonSerializer?

Thanks,
David

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夜血缘 2024-08-21 14:30:09

您是否使用 DataContractJsonSerializer 类?

如果是这样...

将此属性添加到您的 Elements 字段

[DataMember(Name = "elements")] 

SO问题建议如何将 JsonScriptSerializer 的使用覆盖为 JsonDataContractSerializer。

善良,

Are you using the DataContractJsonSerializer class?

If so ...

Add this attribute to you Elements field

[DataMember(Name = "elements")] 

This SO question suggests how to override the use of JsonScriptSerializer to JsonDataContractSerializer.

Kindness,

Dan

回眸一遍 2024-08-21 14:30:09

不幸的答案是,你做不到。话虽如此,我目前正在开发一个模块,该模块将通过在运行时生成一个匿名对象来扩展任何对象,该匿名对象将遵循属性(例如 JsonIgnore 或 JsonProperty)的规则。当我有东西的时候我会发布更多。

The unfortunate answer is, you cannot do it. Having said that, I am currently developing a module that will extend any object by producing at runtime an anonymous object that will follow rules from attributes, such as JsonIgnore or JsonProperty. I'll post more when I have something.

咽泪装欢 2024-08-21 14:30:09

正确的属性是 JsonPropertyName.

The correct attribute for this is JsonPropertyName.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文