确保JSON键在.NET中为小写 [英] Ensuring json keys are lowercase in .NET
问题描述
是否有简单的方法在.NET中使用JSON来确保密钥以小写形式发送?
Is there simple way using JSON in .NET to ensure that the keys are sent as lower case?
此刻,我正在使用newtonsoft的Json.NET库,而仅使用
At the moment I'm using the newtonsoft's Json.NET library and simply using
string loginRequest = JsonConvert.SerializeObject(auth);
在这种情况下,auth
只是以下对象
In this case auth
is just the following object
public class Authority
{
public string Username { get; set; }
public string ApiToken { get; set; }
}
这将导致
{"Username":"Mark","ApiToken":"xyzABC1234"}
是否有办法确保username
和apitoken
键通过小写字母出现?
Is there a way to ensure that the username
and apitoken
keys come through as lowercase?
我当然不想简单地通过String.ToLower()
运行它,因为username
和apitoken
的值是大小写混合的.
I don't want to simply run it through String.ToLower()
of course because the values for username
and apitoken
are mixed case.
我意识到我可以通过编程方式手动创建JSON字符串,但是我需要大约20个左右的JSON数据字符串,而且我正在寻找是否可以节省一些时间.我想知道是否有任何已经建立的库可以让您强制小写以创建密钥.
I realise I can programatically do this and create the JSON string manually, but I need this for approx 20 or so JSON data strings and I'm seeing if I can save myself some time. I'm wondering if there are any already built libraries that allow you to enforce lowercase for key creation.
推荐答案
您可以为此创建一个自定义合同解析器.以下合同解析器会将所有密钥都转换为小写:
You can create a custom contract resolver for this. The following contract resolver will convert all keys to lowercase:
public class LowercaseContractResolver : DefaultContractResolver
{
protected override string ResolvePropertyName(string propertyName)
{
return propertyName.ToLower();
}
}
用法:
var settings = new JsonSerializerSettings();
settings.ContractResolver = new LowercaseContractResolver();
var json = JsonConvert.SerializeObject(authority, Formatting.Indented, settings);
将导致:
{"username":"Mark","apitoken":"xyzABC1234"}
如果您始终想使用LowercaseContractResolver
进行序列化,请考虑将其包装在类中,以避免重复自己的操作:
If you always want to serialize using the LowercaseContractResolver
, consider wrapping it in a class to avoid repeating yourself:
public class LowercaseJsonSerializer
{
private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
ContractResolver = new LowercaseContractResolver()
};
public static string SerializeObject(object o)
{
return JsonConvert.SerializeObject(o, Formatting.Indented, Settings);
}
public class LowercaseContractResolver : DefaultContractResolver
{
protected override string ResolvePropertyName(string propertyName)
{
return propertyName.ToLower();
}
}
}
可以这样使用:
var json = LowercaseJsonSerializer.SerializeObject(new { Foo = "bar" });
// { "foo": "bar" }
ASP.NET MVC4/WebAPI
如果您使用的是ASP.NET MVC4/WebAPI,则可以使用Newtonsoft.Json库中的CamelCasePropertyNamesContractResolver
(默认情况下包含).
ASP.NET MVC4 / WebAPI
If you are using ASP.NET MVC4 / WebAPI, you can use a CamelCasePropertyNamesContractResolver
from Newtonsoft.Json library which included by default.
这篇关于确保JSON键在.NET中为小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!