问题描述
我在C#项目中将ServiceStack.Text
用作JSON库,并且尝试使用TypeSerializer.DeserializeFromString
从文件中反序列化字符串.
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
.
我有以下代码:
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
在这里输出正确的JSON字符串,但下一行TypeSerializer.DeserializeFromString
会产生异常:
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.
TypeSerializer
似乎得到一个空字符串.为什么会发生,如何解决?
It seems like TypeSerializer
gets an empty string. Why is it happening and how can it be fixed?
推荐答案
如果Json对您的Object有效,那么它也可能会起作用:
If the Json is valid for your Object this might work as well:
var cacheItem = (CacheItem) JsonSerializer.DeserializeFromString(result, typeof (CacheItem));
这篇关于使用ServiceStack的TypeSerializer进行文件反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!