【问题标题】:how much camel caseing does CamelCasePropertyNamesContractResolver do?CamelCasePropertyNamesContractResolver 做了多少骆驼案?
【发布时间】:2013-05-04 12:33:53
【问题描述】:

像这样使用 JSON.Net:

JsonConvert.SerializeObject(someObject, 
                            Newtonsoft.Json.Formatting.None, 
                            new JsonSerializerSettings() {
                                NullValueHandling = NullValueHandling.Ignore,
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                                ContractResolver = new CamelCasePropertyNamesContractResolver()
                            });

JSON.Net 做了多少驼峰式?

它只是从单词的开头开始的小写字母吗?

例子:

  • somePropertyId -> somePropertyId
  • somePropertyID -> somePropertyID
  • SOMEPropertyID -> somePropertyID
  • SOMEPROPERTYID -> somepropertyid

【问题讨论】:

  • 为什么不试试看呢?制作一个快速的一次性控制台应用程序来测试这种行为应该很容易。

标签: serialization json.net camelcasing jsonserializer sanity-check


【解决方案1】:

这是 CamelCasePropertyNamesContractResolver 所做的,直接来自单元测试:https://github.com/JamesNK/Newtonsoft.Json/blob/95665429a431364327b4bce5332c39fda7819e7b/Src/Newtonsoft.Json.Tests/Utilities/StringUtilsTests.cs#L40-L54

[Test]
public void ToCamelCaseTest()
{
  Assert.AreEqual("urlValue", StringUtils.ToCamelCase("URLValue"));
  Assert.AreEqual("url", StringUtils.ToCamelCase("URL"));
  Assert.AreEqual("id", StringUtils.ToCamelCase("ID"));
  Assert.AreEqual("i", StringUtils.ToCamelCase("I"));
  Assert.AreEqual("", StringUtils.ToCamelCase(""));
  Assert.AreEqual(null, StringUtils.ToCamelCase(null));
  Assert.AreEqual("iPhone", StringUtils.ToCamelCase("iPhone"));
  Assert.AreEqual("person", StringUtils.ToCamelCase("Person"));
  Assert.AreEqual("iPhone", StringUtils.ToCamelCase("IPhone"));
  Assert.AreEqual("i Phone", StringUtils.ToCamelCase("I Phone"));
  Assert.AreEqual(" IPhone", StringUtils.ToCamelCase(" IPhone"));
}

【讨论】:

  • James - 很遗憾,StringUtils 类被标记为内部。我正在使用您的库来创建 JSON,然后我想要一个 HTML 助手来使用相同的驼峰式字符串函数,以便它们始终匹配。但是我不能这样做,因为它被标记为内部
猜你喜欢
  • 2022-01-06
  • 2014-09-14
  • 1970-01-01
  • 1970-01-01
  • 2016-03-08
  • 1970-01-01
  • 2018-11-13
  • 2023-04-02
  • 1970-01-01
相关资源
最近更新 更多