How can I use a reserved keyword as an identifier in my JSON model class?

前端 未结 3 1028
名媛妹妹
名媛妹妹 2020-11-27 07:51

I have never used Web API before, but I need a web service that will accept/return JSON objects and using this seemed like a reasonable thing. It looked pretty simple (if no

3条回答
  •  [愿得一人]
    2020-11-27 08:24

    The class DropDownValues using camel convention:

    class DropDownValues {
        public string[] values { get; set; }
        public string default { get; set; }
    }
    

    You can use prefix @ to passby but it is still not following C# coding convention.

    The better solution which you can both avoid reserved keyword and still use C# coding convention is using CamelCasePropertyNamesContractResolver:

    class DropDownValues {
        public string[] Values { get; set; }
        public string Default { get; set; }
    }
    

    And customize JsonFormatter to avoid convention mismatch between C# and json object as below:

    var jsonFormatter = configuration.Formatters.JsonFormatter;
    jsonFormatter.SerializerSettings = new JsonSerializerSettings()
    {  
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    };
    

提交回复
热议问题