C# JObject & CamelCase 转换与 JSON.Net

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15087340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:00:47  来源:igfitidea点击:

JObject & CamelCase conversion with JSON.Net

c#json.net

提问by Andrea Balducci

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)

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

UPDATEAccording to http://json.codeplex.com/workitem/23853that cannot be done (tnx to @nick_w for the link)

更新根据无法完成的http://json.codeplex.com/workitem/23853(tnx到 @nick_w 的链接)

回答by nick_w

According to this Json.NET issue, when serializing a JObjectthis way the contract resolver is ignored:

根据这个 Json.NET 问题,当以JObject这种方式序列化 a 时,合同解析器将被忽略:

When serializing a JObject the contract resolvers seems to be ignored. Surely this is not how it is supposed to be?
Closed Jan 30, 2013 at 8:50 AM by JamesNK
That does make sense but it is too big a breaking change I'm afraid.

当序列化一个 JObject 时,契约解析器似乎被忽略了。这肯定不是它应该的样子吗?
JamesNK于 2013 年 1 月 30 日上午 8:50关闭
这确实有道理,但恐怕这是一个太大的重大变化。

Inspired by the workaround on that page, you could do something like this:

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

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);

Edit:

编辑:

Good point about the Dictionary<string, object>. So doing it this way skips the additional JsonConvert.SerializeObject, but it also mitigates the need for the ExpandoObject, which is important if you are using .NET 3.5.

关于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);

回答by Steve Benz

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:

这个问题从一个 JObject 开始,想要处理一个驼峰式 JSON 对象。如果您实际上是从一个对象开始并想要获得一个已经被驼峰​​化的 JObject,那么您可以这样做:

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

The resulting 'jo' will be camelcased.

生成的 'jo' 将是驼峰式的。

回答by Adam Hiler

As of thisMay 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.

由于这个2013年5月8日的博客文章由詹姆斯·牛顿国王关于5.0版本Json.NET的,这已经与除“DefaultSettings”的解决。该页面的示例如下,但请阅读该页面以了解 3rd 方库的详细信息。

// 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"
// }

回答by rafiq J

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());

}

}