简体   繁体   English

UWP Json.Convert存储文件

[英]UWP Json.Convert storage files

I am making a UWP app in which I am trying to save storage files picked by user to the local settings by serializing them, and I want to deserialize them and use them again when I want to. 我正在制作一个UWP应用,在其中我试图通过序列化将用户选择的存储文件保存到本地设置,并且我想对它们进行反序列化并在需要时再次使用它们。 it saves IReadOnlyList object to the local settings just fine, but at the time of deserializing it gives and exception, that this method cant return storage files because it doesnt have a constructor for this, something like this. 它将IReadOnlyList对象保存到本地设置就好了,但是在反序列化时给出了一个例外,该方法无法返回存储文件,因为它没有为此的构造函数。 I am posting the code of my both methods of saving and loading data. 我正在发布两种保存和加载数据方法的代码。 please see it and help me... 请看一下并帮助我...

    public static void SaveState<T>(string key, T value)//save method
    {
        //key is provided by me so that i can use it to load the data later.
        var localSettings = ApplicationData.Current.LocalSettings;
        localSettings.Values[key] = JsonConvert.SerializeObject(value);
    }

    public static T LoadState<T>(string key)//loading data
    {
        var localSettings = ApplicationData.Current.LocalSettings;
        if (localSettings.Values.ContainsKey(key))//exception occurs on the below line
            return JsonConvert.DeserializeObject<T>(((string)localSettings.Values[key]));
        return default(T);
    }

and I use these methods as follows:- 我使用这些方法如下:

    var files = StateService.LoadState<IReadOnlyList<StorageFile>>(Playlist);
    //StateService is the class which has these static methods...

Note: when i try to load data with a key which has no data against it in the local settings, it doesnt give any exception and just returns an empty list.but when its supposed to return a filled list of IReadOnlyList then it gives and exception... 注意:当我尝试使用本地设置中没有针对它的数据的键加载数据时,它不给出任何异常并仅返回一个空列表。但是当它应该返回IReadOnlyList的填充列表时,它给出了和异常...

我认为JsonConvert.DeserializeObject尝试实例化IReadOnlyList<StorageFile>但无法实例化接口...您应该使用例如List<StorageFile>作为T来设置和读取列表...

I did something like that before and I had the same problem. 我之前做过类似的事情,但我遇到了同样的问题。 I did different approach instead of trying to save the StorageFile I saved the json content with the key and always my data is in string ( the json data) and I can use JsonConvert.DeserializeObject<T> without problems. 我采取了不同的方法,而不是尝试保存StorageFile,而是使用密钥保存了json内容,并且始终将我的数据存储在字符串(json数据)中,并且我可以JsonConvert.DeserializeObject<T>使用JsonConvert.DeserializeObject<T>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM