Saturday, February 28, 2015

Deserialize to object

Here are both the code for serialization and the classes I serializes.



private async Task writeJsonAsync()
{
// Notice that the write is ALMOST identical ... except for the serializer.

//var myCars = buildObjectGraph();
var groups = await WordsDataSource.GetGroupsAsync();
this.DefaultViewModel["WordsGroups"] = groups;


var serializer = new DataContractJsonSerializer(typeof(IEnumerable<WordsGroup>));
using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(
JSONFILENAME,
CreationCollisionOption.ReplaceExisting))
{
serializer.WriteObject(stream, groups);
}

resultTextBlock.Text = "Write succeeded";
}


[DataContract]
public class WordsItem
{
public WordsItem(String no, String en, String sp)
{
this.No = no;
this.En = en;
this.Sp = sp;
}

[DataMember]
public string No { get; private set; }
[DataMember]
public string En { get; private set; }
[DataMember]
public string Sp { get; private set; }
}


[DataContract]
public class WordsGroup
{
public WordsGroup(int id, String lesson, String info)
{
this.Id = id;
this.Lesson = lesson;
this.Info = info;
this.Items = new ObservableCollection<WordsItem>();
}

[DataMember]
public int Id { get; private set; }
[DataMember]
public string Lesson { get; private set; }
[DataMember]
public string Info { get; private set; }
[DataMember]
public ObservableCollection<WordsItem> Items { get; set; }


public override string ToString()
{
return this.Lesson;
}
}

Thanks, Sigurd F

No comments:

Post a Comment