简体   繁体   中英

how to change newtonsoft.json code to system.text.json

I want to move completely to .NET Core so I need to use System.Text.Json instead of Newtonsoft.Json.

How can I write this code in the 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);
}

Please refer to the official How to migrate from Newtonsoft.Json to System.Text.Json .

There are 3.1 and 5 versions provided. Please note that in 3.1 you can install the 5.0 package to get the new features (for example deserializing fields).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM