【发布时间】: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