Newtonsoft.Json.JsonSerializationException
HResult=0x80131500
Message=Es konnte kein Konstruktor zur Verwendung für den Typ System.Windows.Ink.Stroke gefunden werden . Eine Klasse sollte entweder einen Standardkonstruktor, einen Konstruktor mit Argumenten oder einen Konstruktor haben, der mit dem JsonConstructor-Attribut gekennzeichnet ist. Pfad „Striche[0].DrawingAttributes“, Zeile 4, Position 26.
Source=Newtonsoft.Json
Code zum Speichern/Laden von Klassen:
Code: Select all
class SaveLoad
{
public static void Save(Board board) {
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document";
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.txt)|*.txt";
Nullable result = dlg.ShowDialog();
if (result == true)
{
string outpath = dlg.FileName;
string jsonData = JsonConvert.SerializeObject(board, Newtonsoft.Json.Formatting.Indented);
var myFile = File.Create(outpath);
myFile.Close();
File.WriteAllText(@"" + outpath, jsonData);
}
}
public static Board Load()
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document";
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.txt)|*.txt";
Nullable result = dlg.ShowDialog();
if (result == true)
{
string outpath = dlg.FileName;
string jsonData = File.ReadAllText(outpath);
return JsonConvert.DeserializeObject(jsonData);
}
else { return null; }
}
}
internal class Board
{
public StrokeCollection strokes;
public UIElementCollection elements;
public UIElementCollection elements_serialized = new UIElementCollection(new UIElement(),new FrameworkElement());
public Board(StrokeCollection strokes, UIElementCollection elements) { this.strokes = strokes; this.elements = elements; }
public void Serialize() {
foreach (UIElement element in this.elements) {
elements_serialized.Add(Clone(element));
}
}
public Board getSerialized() {
return new Board(strokes,elements_serialized);
}
public static T Clone(T element)
{
string xaml = XamlWriter.Save(element);
using (StringReader stringReader = new StringReader(xaml))
using (XmlReader xmlReader = XmlReader.Create(stringReader))
return (T)XamlReader.Load(xmlReader);
}
}
Code: Select all
Board board = new Board(mainInk.Strokes, mainInk.Children);
board.Serialize();
SaveLoad.Save(board.getSerialized());
Code: Select all
Board board = SaveLoad.Load();
if (board == null) {
mainInk.Strokes = board.strokes;
mainInk.Children.Clear();
foreach (UIElement element in board.elements)
{
mainInk.Children.Add(Board.Clone(element));
}
}