I'm using json.net to implement the memento pattern for a winform application. I'm using the memento to rollback an object on a failed database transaction. The problem I'm getting is that when deserializing the memento, the getter is called rather than the setter. Let me demonstrate:
class MyClass
{
public int ID { get; set; }
public string field1 { get; set; }
public string field2 { get; set; }
private List<SomeObject> _someObjects;
public List<SomeObject> SomeObjects
{
get
{
if(_someObjects == null)
{
_someObjects = LoadSomeObjectsFromDB();
}
return _someObjects;
}
set
{
_someObjects = value;
}
}
private List<AnotherObject> _anotherObjects;
public List<AnotherObject> AnotherObjects
{
get
{
if(_anotherObjects == null)
{
_anotherObjects= LoadAnotherObjectsFromDB();
}
return _anotherObjects ;
}
set
{
_anotherObjects = value;
}
}
}
*MyObject
, SomeObject
, and AnotherObject
extend the same base class, Model
As you can see from the sample class above, if SomeObjects is not loaded yet, it uses Lazy Loading to load it from the Database. Now When I serialize this object.
string memento = JsonConvert.SerializeObject(obj);
Resulting in
{
"ID": 1,
"field1": "field 1",
"field2": "field 2",
"SomeObjects": [
{
"ID": 1,
},
{
"ID": 2,
},
{
"ID": 3,
}
],
"AnotherObjects": [
{
"ID": 4,
},
{
"ID": 5,
},
{
"ID": 6,
}
]
}
Then subsequently deserialize it.
MyObject obj = JsonConvert.DeserializeObject(memento, typeof(MyObject));
I get an object represented by the following JSON
{
"ID": 1,
"field1": "field 1",
"field2": "field 2",
"SomeObjects": [
{
"ID": 1,
},
{
"ID": 2,
},
{
"ID": 3,
},
{
"ID": 1,
},
{
"ID": 2,
},
{
"ID": 3,
}
],
"AnotherObjects": [
{
"ID": 4,
},
{
"ID": 5,
},
{
"ID": 6,
},
{
"ID": 4,
},
{
"ID": 5,
},
{
"ID": 6,
}
]
}
Too many items in the SomeObjects
and AnotherObjects
List
s
SomeObjects
getter is called, which causes the List to initialize from the DB then the serialized list is Appended to it. Leaving me with more items in the list than desired. But if I remove the Lazy Loading portion
public List<SomeObject> SomeObjects
{
get
{
/*if(_someObjects == null)
{
_someObjects = LoadSomeObjectsFromDB();
}*/
return _someObjects;
}
set
{
_someObjects = value;
}
}
The getter is still called, but returns null. Then json.net calls the setter with value
being a list with the correct number of elements already added, whereas if the getter returns an initalized list, it appends to it never calling ths setter. Why the discrepancy, if a list is already initialized, the getter is called and it is appended to. But if not initialized, the setter is called and it is initialized with a list already filled with objects. Is there a way to make json.net only call the setter during deserialization of a generic List
?
See Question&Answers more detail:
os