.Net Core ControllerBase操作方法JSON序列化设置

时间:2019-11-27 15:18:27

标签: c# asp.net-core asp.net-core-webapi

我正在开发.Net Core 2.2 Web API。我试图利用ControllerBase方法的优势,例如AcceptedAtAction,Ok等。我已经通过Startup.cs中的.AddJsonOptions配置了JsonSerializerSettings。但是,这些操作方法似乎忽略了序列化设置。为了使这些方法符合这些设置,我还需要做其他事情吗?

Startup.cs

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

控制器

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

1 个答案:

答案 0 :(得分:1)

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

相关问题