我如何与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时使用从数据属性名称。我想改变的属性名称是(为'巴'说,改变'富')不同的东西。

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:

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

文件: 序列化属性

Documentation: Serialization Attributes