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

本文探讨如何在使用Json.net进行序列化时更改C#对象的属性名称,包括使用JsonPropertyAttribute、创建自定义解析器和应用NamingStrategy来实现属性重命名的方法。
摘要由CSDN通过智能技术生成

本文翻译自:How can I change property names when serializing with Json.net?

I have some data in a C# DataSet object. 我在C#DataSet对象中有一些数据。 I can serialize it right now using a Json.net converter like this 我现在可以使用像这样的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 data when printing to the .json file. 但是,这将在打印到.json文件时使用data的属性名称。 I would like to change the property names to be something different (say, change 'foo' to 'bar'). 我想将属性名称更改为其他名称(例如,将“ foo”更改为“ bar”)。

In the Json.net documentation , under 'Serializing and Deserializing JSON' → 'Serialization Attributes' it says "JsonPropertyAttribute... allows the name to be customized". Json.net文档中的 “对JSON进行序列化和反序列化”→“序列化属性”下,其显示为“ JsonPropertyAttribute ...允许自定义名称”。 But there is no example. 但是没有例子。 Does anyone know how to use a JsonPropertyAttribute to change the property name to something else? 有谁知道如何使用JsonPropertyAttribute将属性名称更改为其他名称?

( Direct link to documentation ) 直接链接到文档

Json.net's documentation seems to be sparse. Json.net的文档似乎很少。 If you have a great example I'll try to get it added to the official documentation. 如果您有一个很好的例子,我将尝试将其添加到官方文档中。 Thanks! 谢谢!


#1楼

参考:https://stackoom.com/question/auOw/使用Json-net进行序列化时-如何更改属性名称


#2楼

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 有关自定义解析器的更多信息,请点击此处


#3楼

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


#4楼

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 文档: 序列化属性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值