【发布时间】:2015-05-10 18:04:48
【问题描述】:
我想对以下模型进行序列化/反序列化:
public class ReadabilitySettings
{
public ReadabilitySettings() {
}
private bool _reababilityEnabled;
public bool ReadabilityEnabled {
get {
return _reababilityEnabled;
}
set {
_reababilityEnabled = value;
}
}
private string _fontName;
public string FontName {
get {
return _fontName;
}
set {
_fontName = value;
}
}
private bool _isInverted;
public bool IsInverted {
get {
return _isInverted;
}
set {
_isInverted = value;
}
}
public enum FontSizes
{
Small = 0,
Medium = 1,
Large = 2
}
private FontSizes _fontSize;
public FontSizes FontSize { get
{
return _fontSize;
}
set
{
_fontSize = value;
}
}
}
}
我有一个包含以下对象实例的列表:
public class CacheItem<T>
{
public string Key { get; set; }
public T Value { get; set; }
}
我这样填充列表:
list.Add(new CacheItem<ReadabilitySettings>() { Key = "key1", Value = InstanceOfReadabilitySettings };
当我想序列化这个列表时,我会调用:
var json = JsonConvert.SerializeObject (list);
这很好用。没有错误。它给出了以下 json:
[{"Key":"readbilitySettings","Value":{"ReadabilityEnabled":true,"FontName":"Lora","IsInverted":true,"FontSize":2}}]
当我想反序列化我调用的列表时:
var list = JsonConvert.DeserializeObject<List<CacheItem<object>>> (json);
这给了我一个 CacheItem 的列表,它的 Value 属性设置为一个 JObject。到目前为止没有错误。
当我想要调用 ReadabilitySettings 的实际实例时:
var settings = JsonConvert.DeserializeObject<ReadabilitySettings> (cacheItem.Value.ToString ());
我必须调用它,因为 cacheItem.Value 设置为 json 字符串,而不是 ReadabilitySettings 的实例。 json字符串为:
{{ "ReadabilityEnabled": true, "FontName": "Lora", "IsInverted": true, "FontSize": 2 }} Newtonsoft.Json.Linq.JObject
然后我收到此错误:“在 'Reflect.Mobile.Shared.State.ReadabilitySettings' 上将值设置为 'ReadabilityEnabled' 时出错。”
我错过了什么?谢谢!
编辑------
这是引发错误的方法:
public T Get<T> (string key)
{
var items = GetCacheItems (); // this get the initial deserialized list of CacheItems<object> with its value property set to a JObject
if (items == null)
throw new CacheKeyNotFoundException ();
var item = items.Find (q => q.Key == key);
if (item == null)
throw new CacheKeyNotFoundException ();
var result = JsonConvert.DeserializeObject<T> (item.Value.ToString ()); //this throws the error
return result;
}
【问题讨论】: