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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8796618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:28:59  来源:igfitidea点击:

How can I change property names when serializing with Json.net?

c#serializationjson.net

提问by culix

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

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

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

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

但是,这会使用data打印到 .json 文件时的属性名称。我想将属性名称更改为不同的名称(例如,将“foo”更改为“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?

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

(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!

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

采纳答案by Darin Dimitrov

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

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

using Newtonsoft.Json;
// ...

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

Documentation: Serialization Attributes

文档:序列化属性

回答by StingyHyman

If you don't have access to the classes to change the properties, or don't want to always use the same rename property, renaming can also be done by creating a custom resolver.

如果您无权访问类来更改属性,或者不想始终使用相同的重命名属性,也可以通过创建自定义解析器来完成重命名。

For example, if you have a class called MyCustomObject, that has a property called LongPropertyName, you can use a custom resolver like this…

例如,如果您有一个名为 的类MyCustomObject,它有一个名为 的属性LongPropertyName,您可以使用这样的自定义解析器……

public class CustomDataContractResolver : DefaultContractResolver
{
  public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver ();

  protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
  {
    var property = base.CreateProperty(member, memberSerialization);
    if (property.DeclaringType == typeof(MyCustomObject))
    {
      if (property.PropertyName.Equals("LongPropertyName", StringComparison.OrdinalIgnoreCase))
      {
        property.PropertyName = "Short";
      }
    }
    return property;
  }
}

Then call for serialization and supply the resolver:

然后调用序列化并提供解析器:

 var result = JsonConvert.SerializeObject(myCustomObjectInstance,
                new JsonSerializerSettings { ContractResolver = CustomDataContractResolver.Instance });

And the result will be shortened to {"Short":"prop value"}instead of {"LongPropertyName":"prop value"}

结果将缩短为{"Short":"prop value"}而不是{"LongPropertyName":"prop value"}

More info on custom resolvers here

更多关于自定义解析器的信息在这里

回答by JotaBe

There is still another way to do it, which is using a particular NamingStrategy, which can be applied to a class or a property by decorating them with [JSonObject]or [JsonProperty].

还有另一种方式来做到这一点,这是使用特定NamingStrategy,其可以通过与装饰他们被应用到一个类或财产[JSonObject][JsonProperty]

There are predefined naming strategies like CamelCaseNamingStrategy, but you can implement your own ones.

有预定义的命名策略,例如CamelCaseNamingStrategy,但您可以实现自己的命名策略。

The implementation of different naming strategies can be found here: https://github.com/JamesNK/Newtonsoft.Json/tree/master/Src/Newtonsoft.Json/Serialization

不同命名策略的实现可以在这里找到:https: //github.com/JamesNK/Newtonsoft.Json/tree/master/Src/Newtonsoft.Json/Serialization