Home >Backend Development >C++ >How to Override the JsonProperty Attribute During JSON Serialization with Json.NET?

How to Override the JsonProperty Attribute During JSON Serialization with Json.NET?

Linda Hamilton
Linda HamiltonOriginal
2025-01-07 16:06:44709browse

How to Override the JsonProperty Attribute During JSON Serialization with Json.NET?

Overriding JsonPropertyAttribute

when using Json.NET for JSON serialization

In the scenario of JSON serialization using ASP.Net MVC and Json.Net, it is very effective to utilize the [JsonProperty(PropertyName = "shortName")] attribute to optimize the payload size. This approach is useful when the receiver is another .Net application or service because the deserialization reassembles the object hierarchy using the original property names while minimizing the payload size.

However, problems arise when the client is a JavaScript or Ajax application accessed through a browser. The client receives JSON with shortened property names, which prevents optimal usage. This article explores how to programmatically bypass the [JsonProperty(PropertyName = "shortName")] attribute during JSON serialization.

For this purpose, using a custom contract parser is the best solution. Here is the implementation:

<code class="language-csharp">public class LongNameContractResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        // 使用基类生成具有简短名称的JsonProperty
        IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

        // 将简短名称替换为原始属性名称
        foreach (JsonProperty property in properties)
        {
            property.PropertyName = property.UnderlyingName;
        }

        return properties;
    }
}</code>

By integrating a custom parser, you can easily control serialization behavior. Its effectiveness is as follows:

<code class="language-csharp">public class Program
{
    public static void Main(string[] args)
    {
        Foo foo = new Foo
        {
            CustomerName = "Bubba Gump Shrimp Company",
            CustomerNumber = "BG60938"
        };

        Console.WriteLine("--- 使用JsonProperty名称 ---");
        Console.WriteLine(Serialize(foo, false));
        Console.WriteLine();
        Console.WriteLine("--- 忽略JsonProperty名称 ---");
        Console.WriteLine(Serialize(foo, true));
    }

    public static string Serialize(object obj, bool useLongNames)
    {
        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.Formatting = Formatting.Indented;
        if (useLongNames)
        {
            settings.ContractResolver = new LongNameContractResolver();
        }

        return JsonConvert.SerializeObject(obj, settings);
    }
}</code>

Output:

<code class="language-json">--- 使用JsonProperty名称 ---
{
  "cust-num": "BG60938",
  "cust-name": "Bubba Gump Shrimp Company"
}

--- 忽略JsonProperty名称 ---
{
  "CustomerNumber": "BG60938",
  "CustomerName": "Bubba Gump Shrimp Company"
}</code>

The above is the detailed content of How to Override the JsonProperty Attribute During JSON Serialization with Json.NET?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn