JObject & CamelCase conversion with JSON.Net

前端 未结 4 904
忘掉有多难
忘掉有多难 2020-12-06 03:51

How can I convert a generic JObject to camelCase plain json string? I\'ve tried with JsonSerializerSettings but doesn\'t work (Newtonsoft.Json 4.5.11)

[Test]         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-06 04:52

    As of this May 8th, 2013 blog post by James Newton-King regarding the 5.0 release of Json.NET, this has been addressed with the addition of "DefaultSettings". The example from that page follows but read the page for details for 3rd party libraries.

    // settings will automatically be used by JsonConvert.SerializeObject/DeserializeObject
    JsonConvert.DefaultSettings = () => new JsonSerializerSettings
        {
        Formatting = Formatting.Indented,
        ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
    
    Employee e = new Employee
        {
        FirstName = "Eric",
        LastName = "Example",
        BirthDate = new DateTime(1980, 4, 20, 0, 0, 0, DateTimeKind.Utc),
        Department = "IT",
        JobTitle = "Web Dude"
        };
    
    string json = JsonConvert.SerializeObject(e);
    // {
    //   "firstName": "Eric",
    //   "lastName": "Example",
    //   "birthDate": "1980-04-20T00:00:00Z",
    //   "department": "IT",
    //   "jobTitle": "Web Dude"
    // }
    

提交回复
热议问题