c# – JObject和CamelCase与JSON.Net的转换

前端之家收集整理的这篇文章主要介绍了c# – JObject和CamelCase与JSON.Net的转换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何将通用JObject转换为camelCase plain json字符串?
我试过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);

所产生的“乔”将被骆驼草化.

原文链接:https://www.f2er.com/csharp/96815.html

猜你在找的C#相关文章