问题描述
如何将通用JObject转换为camelCase纯json字符串?我已经尝试过使用JsonSerializerSettings,但是不起作用(Newtonsoft.Json 4.5.11)
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]
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);
}
更新根据 http://json.codeplex.com /workitem/23853 无法完成(链接到@nick_w的tnx)
UPDATEAccording to http://json.codeplex.com/workitem/23853 that cannot be done (tnx to @nick_w for the link)
推荐答案
此问题从JObject开始,并且希望使用驼峰式JSON对象.如果您实际上是从一个对象开始,并且想要转到一个已经驼峰包装的JObject,则可以执行以下操作:
This question starts from a JObject and wants to work to a camel-cased JSON object. If you are actually starting from an object and want to get to a JObject that is already camelcased, then you can do this:
var serializer = new JsonSerializer()
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var jo = JObject.FromObject(someDataContract, serializer);
生成的"jo"将被驼峰包装.
The resulting 'jo' will be camelcased.
这篇关于的对象使用JSON.Net进行CamelCase转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!