I need to deserialize some JavaScript object represented in JSON into the appropriate C # class. Given the good features of automatic properties, I would rather have them in these classes, rather than just have fields. Unfortunately, the .NET Serialization engine (at least by default) completely ignores automatic properties on deserialization and only cares about the backing field, which is obviously not present in the JavaScript object.
Given that there is no standard way for the name of the support fields , and frankly, I don’t even want to worry about “letting the JavaScript object look like it used the C # support fields because it sounds a little dirty, the only way I could serialize JavaScript fields in C # properties if I could force the serialization mechanism to somehow ignore the support field and use the property directly.Unfortunately, I can’t understand how this is done, or if it can be done at all. Any ideas will be appreciated.
EDIT . Here is an example:
JavaScript:
function Cat() { this.Name = "Whiskers"; this.Breed = "Tabby"; } var cat = new Cat();
Then "{Name:" Whiskers "} is serialized.
C # Class:
[Serializable()] public class Cat { public string Name { get; set; } public string Breed { get; set; } }
And the deserialization code that fails:
new DataContractJsonSerializer(typeof(Cat)).ReadObject(inputStream);
And the exception shows that he is failing because he is looking for a field of support.
EDIT2 : here's an exception if this helps (no internal exceptions):
System.Runtime.Serialization.SerializationException
"The data contract type 'Test.Cat' cannot be deserialized because the required data members ' <Name>k__BackingField, <Breed>k__BackingField ' were not found."
Tamas Czinege Jun 03 '09 at 16:04 2009-06-03 16:04
source share