Json序列化和反序列化基于接口的集合数组

安装Nuget包:

Install-Package Newtonsoft.Json

 

主要是要加上下面的设置:

JsonSerializerSettings settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All };

 

示例代码:

private void SaveConvertItems()
{
    JsonSerializerSettings settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All };
    var json = JsonConvert.SerializeObject(ConvertItems, Formatting.Indented, settings);
    File.WriteAllText(ConvertItemsPath, json);
}

private IConvertInfo[] LoadConvertItems()
{
    if (File.Exists(ConvertItemsPath))
    {
        var json = File.ReadAllText(ConvertItemsPath);
        JsonSerializerSettings settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All };
        var items = JsonConvert.DeserializeObject<IConvertInfo[]>(json, settings);
        items.ForEach(s => ConvertController.Instance.UpdateConvertInfo(s));

        return items;
    }

    return null;
}

 

posted @ 2022-01-18 17:27  wzwyc  阅读(140)  评论(0编辑  收藏  举报