使用 Json.net 序列化时如何更改属性名称?

问题描述:

我在 C# DataSet 对象中有一些数据.我现在可以使用这样的 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);

但是,这在打印到 .json 文件时使用来自 data 的属性名称.我想将属性名称更改为不同的名称(例如,将foo"更改为bar").

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').

Json.net 文档中的序列化和反序列化 JSON"下→序列化属性"显示JsonPropertyAttribute ... 允许自定义名称".但是没有例子.有谁知道如何使用 JsonPropertyAttribute 将属性名称更改为其他名称?

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?

(文档的直接链接)

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

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] 属性装饰您希望控制其名称的属性,该属性允许您指定不同的名称:

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