如何将 newtonsoft.json 代码更改为 system.text.json
how to change newtonsoft.json code to system.text.json
我想完全迁移到 .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);
}
请参考官方How to migrate from Newtonsoft.Json to System.Text.Json.
提供了3.1和5版本。请注意,在 3.1 中,您可以安装 5.0 包以获得新功能(例如反序列化字段)。
我想完全迁移到 .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);
}
请参考官方How to migrate from Newtonsoft.Json to System.Text.Json.
提供了3.1和5版本。请注意,在 3.1 中,您可以安装 5.0 包以获得新功能(例如反序列化字段)。