JObject & CamelCase conversion with JSON.Net

前端 未结 4 898
忘掉有多难
忘掉有多难 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:33

    According to this Json.NET issue, when serializing a JObject this way the contract resolver is ignored:

    When serializing a JObject the contract resolvers seems to be ignored. Surely this is not how it is supposed to be?
    Closed Jan 30, 2013 at 8:50 AM by JamesNK
    That does make sense but it is too big a breaking change I'm afraid.

    Inspired by the workaround on that page, you could do something like this:

    var jo = new JObject();
    jo["CamelCase"] = 1;
    
    string json = JsonConvert.SerializeObject(jo);
    var jObject = JsonConvert.DeserializeObject(json);
    
    var settings = new JsonSerializerSettings()
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    };
    
    var serialized = JsonConvert.SerializeObject(jObject, settings);
    
    Assert.AreEqual("{\"camelCase\":1}", serialized);
    

    Edit:

    Good point about the Dictionary. So doing it this way skips the additional JsonConvert.SerializeObject, but it also mitigates the need for the ExpandoObject, which is important if you are using .NET 3.5.

    Dictionary jo = new Dictionary();
    jo.Add("CamelCase", 1);
    
    var settings = new JsonSerializerSettings()
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    };
    
    var serialized = JsonConvert.SerializeObject(jo, settings);
    
    Assert.AreEqual("{\"camelCase\":1}", serialized);
    

提交回复
热议问题