过程:
创建Player
类。
创建播放器List<Player>()
。
将玩家添加到列表中。
写一个json
串行文件。
当我点击writeJson
按钮时,我收到错误:
"Type `'EditPlayers.Player'` cannot be serialized. Consider marking it with the
`DataContractAttribute` attribute, and marking all of its members you want serialized
with the `DataMemberAttribute` attribute. If the type is a collection, consider marking
it with the `CollectionDataContractAttribute`.See the Microsoft .NET Framework
documentation for other supported types."
问题:
如何使用List<Player>()
标记CollectionDataContractAttribute
。
class Player
{
public int MemberId { get; set; }
public int Gender { get; set; }
public string LName { get; set; }
public string FName { get; set; }
public int Tee { get; set; }
public int Team { get; set; }
public int Flight { get; set; }
public int Ohc { get; set; }
public decimal HcIx { get; set; }
}
private async void writeJason_Click(object sender, RoutedEventArgs e)
{
try
{
await writeJsonAsync();
}
catch
{
}
}
private async void readJason_Click(object sender, RoutedEventArgs e)
{
await deserializerJsonAsync();
}
private List<Player> buildObjectGraph()
{
var players = new List<Player>();
players.Add(new Player() {MemberId=1, Gender=0, LName="Player", FName="New", Tee=1, Team=0, Flight=0, Ohc=0, HcIx=0M});
players.Add(new Player() {MemberId=2, Gender=0, LName="Draw", FName="Blind", Tee=1, Team=0, Flight=0, Ohc=0, HcIx=0M});
players.Add(new Player() {MemberId=3, Gender=0, LName="Moles", FName="Mike", Tee=1, Team=4, Flight=1, Ohc=2, HcIx=2.0M});
players.Add(new Player() {MemberId=4, Gender=0, LName="Broemeling", FName="Donald", Tee=1, Team=4, Flight=2, Ohc=10, HcIx=10.0M});
players.Add(new Player() {MemberId=5, Gender=0, LName="Nelson", FName="David", Tee=1, Team=4, Flight=3, Ohc=11, HcIx=11.7M});
players.Add(new Player() {MemberId=6, Gender=0, LName="Moles", FName="David", Tee=1, Team=4, Flight=4, Ohc=20, HcIx=20.0M});
players.Add(new Player() {MemberId=7, Gender=0, LName="Player", FName="A", Tee=1, Team=1, Flight=1, Ohc=0, HcIx=0M});
players.Add(new Player() {MemberId=8, Gender=0, LName="Player", FName="B", Tee=1, Team=1, Flight=2, Ohc=0, HcIx=0M});
players.Add(new Player() {MemberId=9, Gender=0, LName="Player", FName="C", Tee=1, Team=1, Flight=3, Ohc=0, HcIx=0M});
players.Add(new Player() {MemberId=10,Gender=0, LName="Player", FName="D", Tee=1, Team=1, Flight=4, Ohc=0, HcIx=0M});
return players;
}
private async Task writeJsonAsync()
{
var allPlayers = buildObjectGraph();
var serializer = new DataContractJsonSerializer(typeof(List<Player>));
//using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(
// JSONFILENAME,
// CreationCollisionOption.ReplaceExisting))
using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(
JSONFILENAME, CreationCollisionOption.ReplaceExisting))
{
serializer.WriteObject(stream, allPlayers);
}
resultTextBlock.Text = "Write succeeded";
}