我在WebApiConfig中有一节:
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
但是有一个类,我想要完整的属性名称(大写)。
有没有办法覆盖单个案例的默认转换?我从API方法返回HttpResponseMessage
。
[HttpGet]
[Route("lang/{lang}")]
public HttpResponseMessage GetTranslation(TranslateLang lang)
{
var translations = new Translate().GetLibrary()
.Where(t => t.LangsTranslations.Any(l => l.Language == lang))
.ToDictionary(
l => l.Key,
l => l.LangsTranslations.First(x => x.Language == lang).Text
);
return Request.CreateResponse(HttpStatusCode.OK, translations);
}
THX。
答案 0 :(得分:0)
解决方案:
自定义ContractResolver
public class UpperCaseContractResolver : DefaultContractResolver
{
public static readonly UpperCaseContractResolver Instance = new UpperCaseContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
property.PropertyName = property.PropertyName.ToUpper();
return property;
}
}
用法:
[HttpGet]
[Route("lang/{lang}")]
public HttpResponseMessage GetTranslation(TranslateLang lang)
{
var translations = new Translate().GetLibrary()
.Where(t => t.LangsTranslations.Any(l => l.Language == lang))
.ToDictionary(
l => l.Key,
l => l.LangsTranslations.First(x => x.Language == lang).Text
);
var formatter = new JsonMediaTypeFormatter();
var json = formatter.SerializerSettings;
json.ContractResolver = new UpperCaseContractResolver();
return Request.CreateResponse(HttpStatusCode.OK, translations, formatter);
}