You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
SAE-2.01/MCTG/DataPersistence/DataContractJSON.cs

73 lines
2.7 KiB

using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace DataPersistence
{
public class DataContractJSON : IDataManager
{
private string _jsonFolderPath;
private DataContractJsonSerializerSettings _dataContractJsonSerializerSettings;
public DataContractJSON(string jsonFolderPath = "",
DataContractJsonSerializerSettings? dataContractJsonSerializerSettings = null)
{
_jsonFolderPath = jsonFolderPath;
if (dataContractJsonSerializerSettings is null)
_dataContractJsonSerializerSettings = new DataContractJsonSerializerSettings()
{
KnownTypes = new[] { typeof(Recipe) }
};
else
_dataContractJsonSerializerSettings = dataContractJsonSerializerSettings;
}
public void Export<T>(T obj, string pathToExport) where T : class
{
throw new NotImplementedException();
}
public KeyValuePair<string, T> Import<T>(string pathToImport) where T : class
{
throw new NotImplementedException();
}
public Dictionary<string, List<object>> Load()
{
Dictionary<string, List<object>>? elements = new Dictionary<string, List<object>>();
var jsonSerializer = new DataContractJsonSerializer(typeof(Dictionary<string, List<object>>), _dataContractJsonSerializerSettings);
using (FileStream stream = File.OpenRead(Path.Combine(_jsonFolderPath, "data.json")))
{
elements = jsonSerializer.ReadObject(stream) as Dictionary<string, List<object>>;
}
if (elements is null)
throw new ArgumentNullException("elements");
return elements;
}
public void Save(Dictionary<string, List<object>> elements)
{
var jsonSerializer = new DataContractJsonSerializer(typeof(Dictionary<string, List<object>>), _dataContractJsonSerializerSettings);
using (FileStream stream = File.Create(Path.Combine(_jsonFolderPath, "data.json")))
{
using (var jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(
stream: stream,
encoding: System.Text.Encoding.UTF8,
ownsStream: false,
indent: true))
{
jsonSerializer.WriteObject(jsonWriter, elements);
}
}
}
}
}