I want so serialize/deserialize the following model:
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;
}
}
}
}
I have a list containing instances of the following object:
public class CacheItem<T>
{
public string Key { get; set; }
public T Value { get; set; }
}
I populate the list like so:
list.Add(new CacheItem<ReadabilitySettings>() { Key = "key1", Value = InstanceOfReadabilitySettings };
When I want to serialize this list I call:
var json = JsonConvert.SerializeObject (list);
This works fine. No errors. It gives the following json:
[{"Key":"readbilitySettings","Value":{"ReadabilityEnabled":true,"FontName":"Lora","IsInverted":true,"FontSize":2}}]
When I want to deserialize the list I call:
var list = JsonConvert.DeserializeObject<List<CacheItem<object>>> (json);
This gives me a list of CacheItem's with it's Value property set to a JObject. No errors so far.
When I want the actual instance of ReadabilitySettings I call:
var settings = JsonConvert.DeserializeObject<ReadabilitySettings> (cacheItem.Value.ToString ());
I have to call this since the cacheItem.Value is set to a json string, not to an instance of ReadabilitySettings. The json string is:
{{ "ReadabilityEnabled": true, "FontName": "Lora", "IsInverted": true, "FontSize": 2 }} Newtonsoft.Json.Linq.JObject
Then I get this error: "Error setting value to 'ReadabilityEnabled' on 'Reflect.Mobile.Shared.State.ReadabilitySettings'."
What am I missing? Thanks!
EDIT------
This is the method that throws the error:
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;
}