我在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
更多推荐
发布评论