如何 return 以数字开头的字段

How to return a field that starts with a digit

我使用 ASP.NET Core WebAPI 并且我的方法调用应该 return 以下数据:

 { "10v_module": 1, "core_module": 2 }

由于 C# 属性 不可能以数字开头,我将如何做到这一点?

谢谢!

您可以使用 JsonPropertyAttribute 为 C# class 的 属性 提供一个以数字开头的 Json 属性 名称。

[JsonProperty("10v_module")]
public string Tenv_module {get;set;}

它会像

    class Program
    {
        public static void Main()
        {
            string s = "{ \"10v_module\": 1, \"core_module\": 2 }";
            jsonData obj = JsonConvert.DeserializeObject<jsonData>(s);
        }
    }

    public class jsonData
    {
        [JsonProperty("10v_module")]
        public int v_module { get; set; }

        [JsonProperty("core_module")]
        public int core_module { get; set; }
    }

使用 JSON.NET,您只需添加 JsonProperty 属性并指定其出现在结果 JSON

中的自定义名称