.Net C# Newtonsoft 在 DeserializeObject 时出现默认属性问题

.Net C# Newtonsoft issue with default attribute while DeserializeObject

我正在为 JSON 字符串使用 Newtonsoft 来反序列化对象,但我无法获得默认值 attribute/properties

{
   "displayName": "Token",
   "name": "token",
   "type": "string",
   "default": ""
}

C#代码

public class ItemProperties
{
   public string displayName { get; set; }
   public string name { get; set; }
   public string type { get; set; }

   [JsonPropertyName("default")]
   public dynamic defaultValue{ get; set; }
}

我发现我的答案应该可以使用访问您可以在 C# 中使用关键字作为标识符,方法是在它们前面加上 @

C#代码

public class ItemProperties
{
   public string displayName { get; set; }
   public string name { get; set; }
   public string type { get; set; }

   public dynamic @default { get; set; }
}

那么你就可以像objItem.@default一样访问了。

您正在使用 JsonPropertyNameAttribute,它是 System.Text.Json 的一部分。当您使用 Json.NET (Newtonsoft.Json) 时,您需要 JsonPropertyAttribute。我实际上会将其应用于 all 属性,然后将它们重命名为具有惯用的 C# 名称。这是一个完整的例子:

using Newtonsoft.Json;
using System;
using System.IO;

public class ItemProperties
{
    [JsonProperty("displayName")]
    public string DisplayName { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("default")]
    public dynamic DefaultValue { get; set; }
}

class Program
{
    static void Main()
    {
        string json = File.ReadAllText("test.json");
        var properties = JsonConvert.DeserializeObject<ItemProperties>(json);
        Console.WriteLine($"DisplayName: {properties.DisplayName}");
        Console.WriteLine($"Name: {properties.Name}");
        Console.WriteLine($"Type: {properties.Type}");
        Console.WriteLine($"DefaultValue: {properties.DefaultValue}");
    }
}

样本JSON:

{
  "displayName": "x",
  "name": "y",
  "type": "z",
  "default": 10
}

输出:

DisplayName: x
Name: y
Type: z
DefaultValue: 10