对象&使用 JSON.Net 进行驼峰式转换

JObject amp; CamelCase conversion with JSON.Net(对象amp;使用 JSON.Net 进行驼峰式转换)
本文介绍了对象&使用 JSON.Net 进行驼峰式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何将通用 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 无法完成(tnx 到 @nick_w 获取链接)

UPDATE According 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 进行驼峰式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Force JsonConvert.SerializeXmlNode to serialize node value as an Integer or a Boolean(强制 JsonConvert.SerializeXmlNode 将节点值序列化为整数或布尔值)
Using JSON to Serialize/Deserialize TimeSpan(使用 JSON 序列化/反序列化 TimeSpan)
Could not determine JSON object type for type quot;Classquot;(无法确定类型“Class的 JSON 对象类型.)
How to deserialize a JSONP response (preferably with JsonTextReader and not a string)?(如何反序列化 JSONP 响应(最好使用 JsonTextReader 而不是字符串)?)
how to de-serialize JSON data in which Timestamp it-self contains fields?(如何反序列化时间戳本身包含字段的JSON数据?)
JSON.Net custom contract serialization and Collections(JSON.Net 自定义合约序列化和集合)