JObject&使用JSON.Net进行CamelCase转换

时间:2013-02-26 10:58:30

标签: c# json.net

如何将通用JObject转换为camelCase普通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);
}

更新 根据{{​​3}}无法完成(tnx到@nick_w的链接)

4 个答案:

答案 0 :(得分:31)

这个问题从一个JObject开始,想要使用一个基于驼峰的JSON对象。如果你实际上是从一个对象开始并且想要找到一个已经传承的JObject,那么你可以这样做:

var serializer = new JsonSerializer()
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var jo = JObject.FromObject(someDataContract, serializer);

由此产生的'jo'将会被传播。

答案 1 :(得分:12)

根据this Json.NET issue,当以这种方式序列化JObject时,合约解析程序会被忽略:

  

在序列化JObject时,合同解析器似乎被忽略了。当然这不应该是怎么回事?   
截止日期:2013年1月30日上午8:50 JamesNK   
这确实有意义,但恐怕这是一个太大的突破性改变。

受该页面上的变通方法的启发,您可以执行以下操作:

var jo = new JObject();
jo["CamelCase"] = 1;

string json = JsonConvert.SerializeObject(jo);
var jObject = JsonConvert.DeserializeObject<ExpandoObject>(json);

var settings = new JsonSerializerSettings()
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

var serialized = JsonConvert.SerializeObject(jObject, settings);

Assert.AreEqual("{\"camelCase\":1}", serialized);

修改

关于Dictionary<string, object>的好点。这样做可以跳过额外的JsonConvert.SerializeObject,但它也减轻了对ExpandoObject的需求,这对于使用.NET 3.5非常重要。

Dictionary<string, object> jo = new Dictionary<string, object>();
jo.Add("CamelCase", 1);

var settings = new JsonSerializerSettings()
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

var serialized = JsonConvert.SerializeObject(jo, settings);

Assert.AreEqual("{\"camelCase\":1}", serialized);

答案 2 :(得分:5)

As of this May 8th, 2013 blog post by James Newton-King regarding the 5.0 release of Json.NET, this has been addressed with the addition of "DefaultSettings". The example from that page follows but read the page for details for 3rd party libraries.

// settings will automatically be used by JsonConvert.SerializeObject/DeserializeObject
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
    {
    Formatting = Formatting.Indented,
    ContractResolver = new CamelCasePropertyNamesContractResolver()
    };

Employee e = new Employee
    {
    FirstName = "Eric",
    LastName = "Example",
    BirthDate = new DateTime(1980, 4, 20, 0, 0, 0, DateTimeKind.Utc),
    Department = "IT",
    JobTitle = "Web Dude"
    };

string json = JsonConvert.SerializeObject(e);
// {
//   "firstName": "Eric",
//   "lastName": "Example",
//   "birthDate": "1980-04-20T00:00:00Z",
//   "department": "IT",
//   "jobTitle": "Web Dude"
// }

答案 3 :(得分:0)

public static JsonSerializer FormattingData()
{
   var jsonSerializersettings = new JsonSerializer {
   ContractResolver = new CamelCasePropertyNamesContractResolver() };
   return jsonSerializersettings;
}


public static JObject CamelCaseData(JObject jObject) 
{   
   var expandoConverter = new ExpandoObjectConverter();
   dynamic camelCaseData = 
   JsonConvert.DeserializeObject(jObject.ToString(), 
   expandoConverter); 
   return JObject.FromObject(camelCaseData, FormattingData());

}