XML在Android应用程序中序列化和反序列化列表数据

时间:2016-06-22 18:29:47

标签: c# android xml serialization xamarin

所以我试图反序列化和序列化List。

问题:列表(list1)没有保存到名为“ListData”的文件中,如果尚未存在,则应该创建到android内部存储中的文档文件夹中。

我认为该文件可能无法正常创建或文件路径不正确。下面是它应该如何运作,但这不能解释上面的问题。

我想将文件名保存为类似“ListData”的内容。 此外,需要将其保存到内部存储的某个位置,例如应用程序的Data文件夹或内部存储中的Documents。

以下是我对代码的看法,但我似乎无法在其他地方找到任何帮助来解决我的问题。它不起作用,任何解决我想要它的方法的想法?

代码:

public abstract class DataHandler
{
    public static void SaveLists()
    {
        string filePath = Android.OS.Environment.DirectoryDocuments;
        string fileName = "ListData";

        XmlSerializer serializer = new XmlSerializer(typeof(List<Item>));
        Stream writer = new FileStream(filePath, FileMode.Create);

        serializer.Serialize(writer, _LISTFROMANOTHERCLASS_);

        writer.Close();
    }

    public static void LoadLists()
    {
        string filePath = Android.OS.Environment.DirectoryDocuments;
        string fileName = "ListData";

        XmlSerializer serializer = new XmlSerializer(typeof(List<Item>));
        Stream reader = new FileStream(filePath, FileMode.Open);
        List<Item> list1 = new List<Item>();

        list1 = (List<Item>) serializer.Deserialize(reader);
        _LISTFROMANOTHERCLASS_ = list1;

        reader.Close();

    }
}

2 个答案:

答案 0 :(得分:1)

您好我已经编写了一个类来执行这些操作,但使用JSON serlization检查是否有助于它使用MVVM Cross,它已编写代码来加密和解密数据,您可以避免这些部分

 public class PersistantStorageHelper<T>
    {
        IMvxFileStoreAsync _mvxFileStoreAsync;
        IMvxFileStore _mvxFileStore;
        EDEngine bcEngine = new EDEngine(new AesEngine(), Encoding.UTF8);
        string currentkey_temp_dev = "AthulHarikumar00";//This static key is not being used it is a just a place holder

        public PersistantStorageHelper() {
            this._mvxFileStore = Mvx.Resolve<IMvxFileStore>();
            this._mvxFileStoreAsync = Mvx.Resolve<IMvxFileStoreAsync>();
            bcEngine.SetPadding(new Pkcs7Padding());
            currentkey_temp_dev = Constants.PassPhrase.Substring(4, 12)+"Road";
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public async Task<T> GetPersistantObject(T obj)
        {
            var fileName = (typeof(T).ToString().Replace(".", "_"));
           var x= await GetPersistantObject(obj, fileName);
            return x;
        }
        /// <summary>
        /// If object exists returns the object else saves a plain object and returns it
        /// </summary>
        /// <param name="obj">empty placeholder object</param>
        /// <returns>Filesystem object</returns>
        public async Task<T> GetPersistantObject( T obj,string fileName) {

            List<string> files = new List<string>(_mvxFileStore.GetFilesIn(_mvxFileStore.NativePath("")));
            fileName = _mvxFileStore.NativePath(fileName);

            if (!files.Contains(fileName))
            {
                var objJson = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

                objJson= bcEngine.Encrypt(objJson, currentkey_temp_dev);
                await _mvxFileStoreAsync.WriteFileAsync(fileName,objJson);
            }
            else {
                try
                {

                    var temp = await _mvxFileStoreAsync.TryReadTextFileAsync(fileName);
                    var str = bcEngine.Decrypt(temp.Result, currentkey_temp_dev);
                    obj = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);
                }
                catch(Exception e) {
                    var objJson = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

                    objJson = bcEngine.Encrypt(objJson, currentkey_temp_dev);
                    await _mvxFileStoreAsync.WriteFileAsync(fileName, objJson);
                }
            }

            return obj;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public async Task<T> SetPersistantObject(T obj)
        {
            var fileName = _mvxFileStore.NativePath(typeof(T).ToString().Replace(".", "_"));
            var temp = await SetPersistantObject(obj, fileName);
            return temp;

        }
        /// <summary>
        /// Saves object to persistant storage with encryption
        /// </summary>
        /// <param name="obj">object to be stored</param>
        /// <returns>Saved object</returns>
        public async Task<T> SetPersistantObject(T obj,string fileName)
        {

            List<string> files = new List<string>(_mvxFileStore.GetFilesIn(_mvxFileStore.NativePath("")));
             fileName = _mvxFileStore.NativePath(fileName);


                var objJson = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
            objJson = bcEngine.Encrypt(objJson, currentkey_temp_dev);
            await _mvxFileStoreAsync.WriteFileAsync(fileName, objJson);



            return obj;
        }
    }

答案 1 :(得分:0)

java.util.List不可序列化,但是java.util.ArrayList是。因此,只需在两个站点上将List更改为ArrayList(在variablename之前,在构造函数之前)。还要检查你的Item是否实现了Serializable