1

使用JSON.Net這樣的:CamelCasePropertyNamesContractResolver做了多少駱駝?

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

多少駱駝caseing不JSON.Net嗎?

它只是從單詞的開頭開始的小寫字母嗎?

例子:

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

爲什麼不試試看看?應該很容易做出一個快速一扔控制檯應用程序來測試這種行爲。 – 2013-05-09 22:34:05

回答

5

這裏是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")); 
} 
+0

正是我在找的,謝謝! – Homer 2013-05-10 13:12:19

+2

詹姆斯 - 這是一個恥辱,這是StringUtils類標記爲內部。我使用你的庫來創建JSON,然後我想要一個HTML助手使用相同的駝峯字符串函數,以便它們始終匹配。不過,我不能這樣做,因爲它的內部標記 – 2013-06-16 14:27:20