我们有一个系统,其中用C#编写的服务器实现REST接口,客户端用JS编写,大多数数据作为JSON传递。
在某种程度上,camelCase和PascalCase世界之间存在冲突。
这些参数主要来自服务器中的名称,并且都在PascalCase中。
JS前端是使用camelCase编写的,并期望服务器接受这样的参数,因为JSON来自JS世界。
什么构成可接受的解决方案,为什么?
答案 0 :(得分:1)
对于Web API方法的参数使用" camelCase",我认为这提出了.NET中方法参数的名称约定
对于属性,请使用JSON serialization attributes
public class Person
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
序列化对象将如下所示:
{ "id": 10, "name": "My Name" }
使用这种方法,您的C#代码将保留PascalCase,客户端(Javascript)将使用camelCase。
答案 1 :(得分:0)
我不知道它是否是完整的答案,因为目前尚不清楚你想要达到的目标。
显然C#是Pascal案例,JSON是Camel案例。
因此,对于我们的Web ASP.Net Web API应用程序,我们已经为Json.NET实现了DataConverter:
// Prompts the user for a binary number and then returns the decimal equivalent without making use of conditionals/loops
int first_bit;
int second_bit;
int third_bit;
int fourth_bit;
int decimal;
cout << "What is the first digit in your 4-bit binary number?" << endl;
cin >> first_bit;
cout << "What is the second digit in your 4-bit binary number?" << endl;
cin >> second_bit;
cout << "What is the third digit in your 4-bit binary number?" << endl;
cin >> third_bit;
cout << "What is the fourth digit in your 4-bit binary number?" << endl;
cin >> fourth_bit;
cout << "Your 4-bit binary number is " << first_bit << second_bit << third_bit << fourth_bit << endl;
decimal = ((first_bit) * pow(2, 3)) + ((second_bit) * pow(2, 2)) + ((third_bit) * pow(2, 1)) + ((fourth_bit) * pow(2, 0));
cout << "The decimal equivalent of " << first_bit << second_bit << third_bit << fourth_bit << " is " << decimal << endl;
它会转换&#34; someProperty&#34; to&#34; SomeProperty&#34;当JSON转换为C#对象和&#34; SomeProperty&#34; to&#34; someProperty&#34;在相反的方向。它允许我们在API控制器中使用动态关键字(对于ASP.Net Core项目,输入参数需要属性[FromBody]。)