.NET에서 json 키가 소문자인지 확인
.NET에서 JSON을 사용하여 키가 소문자로 전송되도록하는 간단한 방법이 있습니까?
현재 저는 newtonsoft의 Json.NET 라이브러리를 사용하고 있습니다.
string loginRequest = JsonConvert.SerializeObject(auth);
이 경우 auth
는 다음 개체입니다
public class Authority
{
public string Username { get; set; }
public string ApiToken { get; set; }
}
결과
{"Username":"Mark","ApiToken":"xyzABC1234"}
username
및 apitoken
키가 소문자로 표시 되도록하는 방법이 있습니까?
나는 단순히 통해 그것을 실행하지 않으 String.ToLower()
에 대한 값 때문에 과정 username
과이 apitoken
혼합 된 경우이다.
프로그래밍 방식으로이 작업을 수행하고 JSON 문자열을 수동으로 만들 수 있다는 것을 알고 있지만 약 20 개 정도의 JSON 데이터 문자열에이 작업이 필요하며 시간을 절약 할 수 있는지 확인하고 있습니다. 키 생성에 소문자를 적용 할 수있는 이미 빌드 된 라이브러리가 있는지 궁금합니다.
이를 위해 사용자 지정 계약 해결자를 만들 수 있습니다. 다음 계약 해결 프로그램은 모든 키를 소문자로 변환합니다.
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);
Wil 결과 :
{"username":"Mark","apitoken":"xyzABC1234"}
항상을 사용하여 직렬화 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();
}
}
}
다음과 같이 사용할 수 있습니다.
var json = LowercaseJsonSerializer.SerializeObject(new { Foo = "bar" });
// { "foo": "bar" }
ASP.NET MVC4 / WebAPI
ASP.NET MVC4 / WebAPI를 사용하는 경우 CamelCasePropertyNamesContractResolver
기본적으로 포함 된 Newtonsoft.Json 라이브러리를 사용할 수 있습니다 .
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();
}
}
In Json.NET 9.0.1 and 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 ContractResolver
and thus may be easier to integrate into frameworks that already have their own contract resolvers.
Define LowercaseNamingStrategy
as follows:
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 -
Using
string.ToLowerInvariant()
ensures that the same contract is generated in all locales.To control whether overridden property names, dictionary keys and extension data names are lowercased, you can set
NamingStrategy.OverrideSpecifiedNames
,NamingStrategy.ProcessDictionaryKeys
orNamingStrategy.ProcessExtensionDataNames
(Json.NET 10.0.1 and later) totrue
.You may want to cache the contract resolver for best performance.
If you do not have access to the serializer settings in your framework, you can apply a
NamingStrategy
directly to your object as follows:[JsonObject(NamingStrategyType = typeof(LowercaseNamingStrategy))] public class Authority { public string Username { get; set; } public string ApiToken { get; set; } }
Do not modify the
NamingStrategy
ofCamelCasePropertyNamesContractResolver
. This contract resolver shares type information globally across all of its instances, and so modifying any one instance can have unexpected side effects.
you can use "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);
참고URL : https://stackoverflow.com/questions/6288660/ensuring-json-keys-are-lowercase-in-net
'Programing' 카테고리의 다른 글
지도 저장 (0) | 2020.08.26 |
---|---|
Express.js에서 Node.js를 사용하는 세션은 어떻게 작동합니까? (0) | 2020.08.26 |
함수를 반환하는 함수 (0) | 2020.08.26 |
Laravel orderBy 관계에 (0) | 2020.08.26 |
Windows 10에서 명령 프롬프트가 멈추는 이유는 무엇입니까? (0) | 2020.08.26 |