【发布时间】:2017-04-27 22:59:31
【问题描述】:
所以我试图在我的 xamarin 表单项目中序列化和反序列化一个名为 player 的对象。 这就是 Player 的样子:
public class Player
{
//stores weather the player ended his turn
public bool turnOver = false;
//the name of the player
public string name { get; set; }
//total score of the player
public long score { get; set; }
//coins to buy abillities
public int coins { get; set; }
//array that stores for each ability how much uses left
public int[] abilities = { 2, 2, 2, 2 };
//the levels the player have completed
public List<long> completedLevels;
//player constructor that initializes all the data for initial use
public Player()
{
this.name = "";
score = 0;
coins = 100;
completedLevels = new List<long>();
}
}
我在Android项目中使用这些方法对对象进行序列化和反序列化。
public void Serialize<T>(Player list)
{
//Creating XmlSerializer.
XmlSerializer serializer = new XmlSerializer(typeof(T));
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var filePath = Path.Combine(documentsPath, "data1.xml");
var file = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Write);
var strm = new StreamWriter(file);
//Convert the XML to List
serializer.Serialize(strm, list);
strm.Close();
}
public T GenericDeSerialize<T>()
{
//Creating XmlSerializer for the object
XmlSerializer serializer = new XmlSerializer(typeof(T));
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var filePath = Path.Combine(documentsPath, "data1.xml");
var file = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Read);
var strm = new StreamReader(file);
string text = strm.ReadToEnd();
//Deserialize back to object from XML
T b = (T)serializer.Deserialize(strm);
strm.Close();
return b;
}
现在序列化部分运行良好,但在尝试反序列化时出现异常:
缺少根元素
我查看了生成的 xml,它看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<Player xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<turnOver>false</turnOver>
<abilities>
<int>2</int>
<int>2</int>
<int>2</int>
<int>2</int>
</abilities>
<completedLevels />
<name />
<score>0</score>
<coins>500</coins>
</Player>
我找不到这个问题任何人都可以指出为什么 xmlserializer 可能正在写一些东西而无法读取它? 谢谢
编辑: 这是我现在如何调用它们进行测试的方式,序列化器是具有这两个功能的类。
Serializer ser = new Serializer();
Player p = new Player();
p.coins = 500;
ser.Serialize<Player>(p);
ser.GenericDeSerialize<Player>();
【问题讨论】:
标签: android xml serialization xamarin xamarin.forms