确保 .NET 中的 json 键是小写的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6288660/
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-09-03 15:37:32  来源:igfitidea点击:

Ensuring json keys are lowercase in .NET

.netjsonjson.net

提问by Mark

Is there simple way using JSON in .NET to ensure that the keys are sent as lower case?

有没有在 .NET 中使用 JSON 来确保密钥以小写形式发送的简单方法?

At the moment I'm using the newtonsoft's Json.NET library and simply using

目前我正在使用 newtonsoft 的 Json.NET 库并简单地使用

string loginRequest = JsonConvert.SerializeObject(auth);

In this case authis just the following object

在这种情况下auth只是以下对象

public class Authority
{
    public string Username { get; set; }
    public string ApiToken { get; set; }
}

This results in

这导致

{"Username":"Mark","ApiToken":"xyzABC1234"}

Is there a way to ensure that the usernameand apitokenkeys come through as lowercase?

有没有办法确保usernameapitoken键以小写形式出现?

I don't want to simply run it through String.ToLower()of course because the values for usernameand apitokenare mixed case.

我不想简单地通过运行它String.ToLower(),当然,因为价值观usernameapitoken是混合的情况。

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.

我意识到我可以以编程方式执行此操作并手动创建 JSON 字符串,但是我需要大约 20 个左右的 JSON 数据字符串,我正在查看是否可以节省一些时间。我想知道是否有任何已经构建的库允许您为密钥创建强制使用小写。

回答by alexn

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

Usage:

用法:

var settings = new JsonSerializerSettings();
settings.ContractResolver = new LowercaseContractResolver();
var json = JsonConvert.SerializeObject(authority, Formatting.Indented, settings);

Wil result in:

将导致:

{"username":"Mark","apitoken":"xyzABC1234"}


If you always want to serialize using the LowercaseContractResolver, consider wrapping it in a class to avoid repeating yourself:

如果您总是想使用 进行序列化LowercaseContractResolver,请考虑将其包装在一个类中以避免重复:

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

Which can be used like this:

可以这样使用:

var json = LowercaseJsonSerializer.SerializeObject(new { Foo = "bar" });
// { "foo": "bar" }


ASP.NET MVC4 / WebAPI

ASP.NET MVC4/WebAPI

If you are using ASP.NET MVC4 / WebAPI, you can use a CamelCasePropertyNamesContractResolverfrom Newtonsoft.Json library which included by default.

如果您使用的是 ASP.NET MVC4 / WebAPI,则可以使用CamelCasePropertyNamesContractResolver默认包含的 Newtonsoft.Json 库。

回答by Sagi

protected void Application_Start() {
    JsonConfig.Configure();   
}

public static class JsonConfig
{
    public static void Configure(){
        var formatters = GlobalConfiguration.Configuration.Formatters;
        var jsonFormatter = formatters.JsonFormatter;
        var settings = jsonFormatter.SerializerSettings;

        settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }
}

回答by dbc

In Json.NET 9.0.1and later it is possible to ensure that all property names are converted to lowercase by using a custom NamingStrategy. This class extracts the logic for algorithmic remapping of property names from the contract resolver to a separate, lightweight object that can be set on DefaultContractResolver.NamingStrategy. Doing so avoids the need to create a custom ContractResolverand thus may be easier to integrate into frameworks that already have their own contract resolvers.

Json.NET 9.0.1及更高版本中,可以通过使用自定义NamingStrategy. 这个类从合约解析器中提取属性名称的算法重映射逻辑到一个单独的、轻量级的对象,可以在 上设置DefaultContractResolver.NamingStrategy。这样做避免了创建自定义ContractResolver的需要,因此可能更容易集成到已经拥有自己的合同解析器的框架中。

Define LowercaseNamingStrategyas follows:

定义LowercaseNamingStrategy如下:

public class LowercaseNamingStrategy : NamingStrategy
{
    protected override string ResolvePropertyName(string name)
    {
        return name.ToLowerInvariant();
    }
}

Then serialize as follows:

然后序列化如下:

var settings = new JsonSerializerSettings
{
    ContractResolver = new DefaultContractResolver { NamingStrategy = new LowercaseNamingStrategy() },
};
string loginRequest = JsonConvert.SerializeObject(auth, settings);

Notes -

备注 -

回答by Jorgelig

you can use "JsonProperty":

您可以使用“JsonProperty”:

Usage:

用法:

public class Authority
{
    [JsonProperty("userName")] // or [JsonProperty("username")]
    public string Username { get; set; }
    [JsonProperty("apiToken")] // or [JsonProperty("apitoken")]
    public string ApiToken { get; set; }
}

var json  = JsonConvert.SerializeObject(authority);

回答by workabyte

For me I used a combination of some of the other answers and ended up with this

对我来说,我结合了其他一些答案并最终得到了这个

        return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        });

was closer to a solution to what I was looking for as I was not looking to create my own

更接近于我正在寻找的解决方案,因为我不想创建自己的