将 JsonSerializer Settings 从 JsonSerializer 复制到新的 JsonSeriali



有没有办法从JsonSerializer类中取出设置并在新JsonSerializer中重新实现它们?

似乎没有任何方法可以做这样的事情。我找到的最好的是通过反射调用的私有方法,ApplySerializerSettings .

我正在尝试从WriteJson方法中获取序列化程序并将其复制到新的序列化程序中,对其进行一些调整。具体来说,我想更换ContractResolver.

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)

似乎最好的方法是将所有设置复制到一个新对象中。它们有很多,所以这里有一个很好的扩展方法(从 8.0.3 开始)。

public static class JsonSerializerExtensions
{
  public static JsonSerializer DeepCopy(this JsonSerializer serializer)
  {
    var copiedSerializer = new JsonSerializer
    {
      Context = serializer.Context,
      Culture = serializer.Culture,
      ContractResolver = serializer.ContractResolver,
      ConstructorHandling = serializer.ConstructorHandling,
      CheckAdditionalContent = serializer.CheckAdditionalContent,
      DateFormatHandling = serializer.DateFormatHandling,
      DateFormatString = serializer.DateFormatString,
      DateParseHandling = serializer.DateParseHandling,
      DateTimeZoneHandling = serializer.DateTimeZoneHandling,
      DefaultValueHandling = serializer.DefaultValueHandling,
      EqualityComparer = serializer.EqualityComparer,
      FloatFormatHandling = serializer.FloatFormatHandling,
      Formatting = serializer.Formatting,
      FloatParseHandling = serializer.FloatParseHandling,
      MaxDepth = serializer.MaxDepth,
      MetadataPropertyHandling = serializer.MetadataPropertyHandling,
      MissingMemberHandling = serializer.MissingMemberHandling,
      NullValueHandling = serializer.NullValueHandling,
      ObjectCreationHandling = serializer.ObjectCreationHandling,
      PreserveReferencesHandling = serializer.PreserveReferencesHandling,
      ReferenceResolver = serializer.ReferenceResolver,
      ReferenceLoopHandling = serializer.ReferenceLoopHandling,
      StringEscapeHandling = serializer.StringEscapeHandling,
      TraceWriter = serializer.TraceWriter,
      TypeNameHandling = serializer.TypeNameHandling,
      SerializationBinder = serializer.SerializationBinder,
      TypeNameAssemblyFormatHandling = serializer.TypeNameAssemblyFormatHandling
    };
    foreach (var converter in serializer.Converters)
    {
      copiedSerializer.Converters.Add(converter);
    }
    return copiedSerializer;
  }
}

它很丑,但至少你只需要写一次。要稍微小心,因为属性本身没有深度复制。

下面的答案是片状的,具体取决于您的实施,尤其是在解决合同时。保留它以防万一它对某人有帮助。


所以,我不能完全复制设置,但我找到了一个可能需要考虑的好方法。您只需在锁定的上下文中设置要更改的属性,然后重置它们。

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    var thing = value as IThing;
    if (thing == null)
        throw new ArgumentException($"Writing Json failed because " + 
          "value was not a 'Thing' of type, {typeof(IThing).FullName}");
    JObject jsonThing;
    //If your solution is multithreaded,
    //and is using a shared serializer (which you probably are),
    //you should lock the serializer so that it doesn't accidentally use 
    //the "CustomObjectResolver"
    lock (serializer)
    {
        //Hold the original value(s) to reset later
        var originalContractResolver = serializer.ContractResolver;
        //Set custom value(s)
        serializer.ContractResolver = new CustomObjectResolver();
        //Serialization with custom properties
        jsonThing = JObject.FromObject(value, serializer);
        //Reset original value(s)
        serializer.ContractResolver = originalContractResolver;
    }
    //Finish serializing and write to writer.
}

不确定这是否是主题 - 但由于这是在我的谷歌中搜索克隆 JSONSerializerSettings 时出现的第一篇文章,我想我会留下通知。

我刚刚有一个类似的要求。

在我的.Net Core WebApi解决方案中,我们有一个用于序列化JSON的默认值,具有

jsonSerializaerSettings.NullValueHandling = NullValueHandling.Ignore;

但是在一些端点中,我还想序列化空属性,因为这些端点表示一个数据集。因此,所有对象在序列化时都应具有所有属性。

我尝试了几种方法,然后阅读了选项模式,我偶然发现了IOptionSnapshot - https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.1#reload-configuration-data-with-ioptionssnapshot

因此,我最终将IOptionsSnapshot注入到我的控制器方法中,这给了我默认选项的副本,我可以修改并用于此单个请求。

在下一个请求中,注入的选项将恢复为默认值。

很好,很容易 - 至少对于我的目的。

所以我的样品的最终解决方案是这样的

[HttpPost("dataset", Name = "GetReportDataset")]
public IActionResult GetReportDataset(
    [FromServices]IOptionsSnapshot<MvcJsonOptions> jsonOptions,
    [FromBody]DataSetReport report,
    [FromQuery]int? top)
{
    //Logic to fetch dataset
    var myDataSet = myRepository.GetDataset(report, top);
    var serializerSettings = jsonOptions.Value.SerializerSettings;
    serializerSettings.NullValueHandling = NullValueHandling.Include;
    return new JsonResult(myDataSet, serializerSettings);
}

希望这有助于其他人来这里进行类似的使用。

/安德斯

相关内容

  • 没有找到相关文章

最新更新