File deserialization with ServiceStack's TypeSerializer

佐手、 提交于 2019-12-11 19:04:19

问题


I use ServiceStack.Text as JSON library in my C# project and I'm trying to deserialize a string from file using it's TypeSerializer.DeserializeFromString.

I have the following code:

async public static void TryLoad(Action<JsonArrayObjects> Ok, 
    Action<string> Fail, string key, int offset)
{
    try
    {
        var folder = ApplicationData.Current.LocalFolder;
        var stream = await folder.OpenStreamForReadAsync(key);
        var result = await new StreamReader(stream).ReadToEndAsync();

        Debug.WriteLine(result);
        var cacheItem = TypeSerializer.DeserializeFromString<CacheItem>(result);
        if (cacheItem.IsValid(offset) == true) Ok(cacheItem.Data); else Fail(key);
    }
    catch (Exception)
    {
        Fail(key);
    }
}

Debug.WriteLine here outputs correct JSON string but the next line with TypeSerializer.DeserializeFromString yields an exception:

A first chance exception of type 'System.IndexOutOfRangeException' occurred in Unknown Module.  

It seems like TypeSerializer gets an empty string. Why is it happening and how can it be fixed?


回答1:


If the Json is valid for your Object this might work as well:

 var cacheItem = (CacheItem) JsonSerializer.DeserializeFromString(result, typeof (CacheItem));



回答2:


Problem solved by switching to Json.NET which behaves correctly in this situation.



来源:https://stackoverflow.com/questions/14106865/file-deserialization-with-servicestacks-typeserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!