gpt4 book ai didi

c# - .Net Core ControllerBase Action Method JSON 序列化设置

转载 作者:太空宇宙 更新时间:2023-11-03 11:57:15 25 4
gpt4 key购买 nike

我正在开发 .Net Core 2.2 Web API。我正在尝试利用 ControllerBase 方法,例如 AcceptedAtAction、Ok 等。我已经通过我的 Startup.cs 中的 .AddJsonOptions 配置了我的 JsonSerializerSettings。但是,这些操作方法似乎忽略了序列化设置。为了让这些方法遵循这些设置,我还需要做些什么吗?

启动.cs

.AddJsonOptions(opts =>
{
opts.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Ignore;
opts.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
opts.SerializerSettings.ContractResolver = new EmptyCollectionContractResolver();
})

Controller

return AcceptedAtAction(
nameof(GetPayEntryImport),
new
{
companyId = companyId,
id = timeImportResponseModel.TimeImportFileTrackingId,
version = apiVersion.ToString()
},
timeImportResponseModel);

响应序列化为空数组的空集合,考虑到我正在使用的 ContractResolver,情况不应该如此。

{
"timeImportFileTrackingId": "bd3cd9fc-09c7-4da0-b1d9-eb8863841ed8",
"status": "The file was accepted and is currently being processed.",
"postProcessingResults": [],
"processedData": []
}

EmptyCollectionContractResolver

public class EmptyCollectionContractResolver : CamelCasePropertyNamesContractResolver
{
protected virtual JsonProperty CreateProperty(
MemberInfo member,
MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
Predicate<object> shouldSerialize = property.get_ShouldSerialize();
property.set_ShouldSerialize((Predicate<object>) (obj =>
{
if (shouldSerialize == null || shouldSerialize(obj))
return !this.IsEmptyCollection(property, obj);
return false;
}));
return property;
}

private bool IsEmptyCollection(JsonProperty property, object target)
{
object obj = property.ValueProvider.GetValue(target);
switch (obj)
{
case ICollection collection:
if (collection.Count == 0)
return true;
break;
case null:
return false;
}
if (!typeof (IEnumerable).IsAssignableFrom(property.get_PropertyType()))
return false;
PropertyInfo property1 = property.get_PropertyType().GetProperty("Count");
if (property1 == (PropertyInfo) null)
return false;
return (int) property1.GetValue(obj, (object[]) null) == 0;
}
}

最佳答案

此问题是由我们在 AddMvc 扩展方法中配置 OutputFormatter 引起的。如果你没有配置任何 JsonOutputFormatters,你应该没问题,AddJsonOptions 会提供你需要的。否则,请确保为 JsonOutputFormatter 配置了所需的序列化设置。

关于c# - .Net Core ControllerBase Action Method JSON 序列化设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59073337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com