【问题标题】:How to return a field that starts with a digit如何返回以数字开头的字段
【发布时间】:2017-11-02 12:31:15
【问题描述】:

我使用 ASP.NET Core WebAPI,我有方法调用应该返回以下数据:

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

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

谢谢!

【问题讨论】:

  • 你可以只返回一个 Dictionary 或 Tuple 的集合吗?

标签: c# asp.net asp.net-web-api asp.net-core asp.net-core-webapi


【解决方案1】:

应该是这样的

    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 中的自定义名称

【讨论】:

    【解决方案2】:

    您可以使用JsonPropertyAttribute 为您的 C# 类的属性指定一个以数字开头的 Json 属性名称。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多