【问题标题】:how to change newtonsoft.json code to system.text.json如何将 newtonsoft.json 代码更改为 system.text.json
【发布时间】:2021-04-23 07:32:00
【问题描述】:

我想完全迁移到 .NET Core,所以我需要使用 System.Text.Json 而不是 Newtonsoft.Json。

如何在 System.Text.Json 中编写此代码?

private readonly JsonSerializer _serializer;

_serializer = JsonSerializer.Create(new JsonSerializerSettings
{
  DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate
});

private JObject _jsonSettings;

protected override void LoadSection(string sectionName, object section)
{    
  var jsonSection = _jsonSettings[sectionName];
  if (jsonSection != null)
  {
    using (var reader = jsonSection.CreateReader())
    {
      _serializer.Populate(reader, section);
    }
  }
}

protected override void SaveSection(string sectionName, object section)
{        
  var settings = _jsonSettings ?? new JObject();
  settings[sectionName] = JObject.FromObject(section);
  _jsonSettings = settings;
}

protected override void LoadDefaults()
{
  _jsonSettings = new JObject();
}

private void LoadFromJson(string json)
{
  _jsonSettings = JObject.Parse(json);
}

【问题讨论】:

    标签: c# json system.text.json


    【解决方案1】:

    请参考官方How to migrate from Newtonsoft.Json to System.Text.Json

    提供了 3.1 和 5 版本。请注意,在 3.1 中,您可以安装 5.0 包以获取新功能(例如反序列化字段)。

    【讨论】:

      猜你喜欢
      • 2022-01-06
      • 2022-07-23
      • 2017-09-23
      • 1970-01-01
      • 2020-03-09
      • 2014-01-18
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      相关资源
      最近更新 更多