如何将通用JObject转换为camelCase plain json字符串?
我试过JsonSerializerSettings但不工作(Newtonsoft.Json 4.5.11)
我试过JsonSerializerSettings但不工作(Newtonsoft.Json 4.5.11)
[Test] public void should_convert_to_camel_case() { var serializer = JsonSerializer.Create(new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }); var jo = new JObject(); jo["CamelCase"] = 1; var stringWriter = new StringWriter(); var writer = new JsonTextWriter(stringWriter); serializer.Serialize(writer,jo); var serialized = stringWriter.ToString(); Assert.AreEqual("{\"camelCase\":1}",serialized); }
UPDATE
根据http://json.codeplex.com/workitem/23853不能完成(tnx到@nick_w的链接)
解决方法
这个问题从一个JObject开始,想要工作到一个骆驼的JSON对象.如果你实际上是从一个对象开始,并且想要获得一个已经是camelcased的JObject,那么你可以这样做:
var serializer = new JsonSerializer() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var jo = JObject.FromObject(someDataContract,serializer);
所产生的“乔”将被骆驼草化.