使用Json.net序列化时如何更改属性名称?(How can I change property names when serializing with Json.net?)

编程入门 行业动态 更新时间:2024-10-26 10:30:48
使用Json.net序列化时如何更改属性名称?(How can I change property names when serializing with Json.net?)

我在C#DataSet对象中有一些数据。 我现在可以使用像这样的Json.net转换器来序列化它

DataSet data = new DataSet(); // do some work here to populate 'data' string output = JsonConvert.SerializeObject(data);

但是,当打印到.json文件时,这将使用data的属性名称。 我想将属性名称改成不同的东西(比如说,将'foo'改为'bar')。

在Json.net文档中 ,在“序列化和反序列化JSON”→“序列化属性”下,它说“JsonPropertyAttribute ...允许自定义名称”。 但是没有例子。 有没有人知道如何使用JsonPropertyAttribute将属性名称更改为其他内容?

( 直接链接到文档 )

Json.net的文档似乎很少。 如果您有一个很好的例子,我会尝试将其添加到官方文档中。 谢谢!

I have some data in a C# DataSet object. I can serialize it right now using a Json.net converter like this

DataSet data = new DataSet(); // do some work here to populate 'data' string output = JsonConvert.SerializeObject(data);

However, this uses the property names from data when printing to the .json file. I would like to change the property names to be something different (say, change 'foo' to 'bar').

In the Json.net documentation, under 'Serializing and Deserializing JSON' → 'Serialization Attributes' it says "JsonPropertyAttribute... allows the name to be customized". But there is no example. Does anyone know how to use a JsonPropertyAttribute to change the property name to something else?

(Direct link to documentation)

Json.net's documentation seems to be sparse. If you have a great example I'll try to get it added to the official documentation. Thanks!

最满意答案

您可以使用[JsonProperty]属性来装饰您希望控制其名称的属性,该属性允许您指定其他名称:

[JsonProperty(PropertyName = "FooBar")] public string Foo { get; set; }

文档: 序列化属性

You could decorate the property you wish controlling its name with the [JsonProperty] attribute which allows you to specify a different name:

using Newtonsoft.Json; // ... [JsonProperty(PropertyName = "FooBar")] public string Foo { get; set; }

Documentation: Serialization Attributes

更多推荐

本文发布于:2023-07-16 10:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1126883.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   如何更改   名称   序列化   net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!