Fixing the SerializationException when parsing JSON
Posted: (EET/GMT+2)
Some more problem-solving for today. If you are developing Silverlight applications for the web (or Windows Phone), chances are you will need to parse some JSON coming back from your web backend. In the .NET world, you can use the build-in DataContractJsonSerializer class, part of the System.Runtime.Serialization.Json namespace. This class contains a nice little ReadObject method, which will take a stream with JSON data, and return an object that matches the values in the input.
However, the problem is: you as a developer need to first construct a class (or classes) that match the incoming data. If you are just starting, you might use your existing C# or .NET knowledge, and create an class with public properties to match the JSON. However, this quickly leads to errors, such as the following:
System.Runtime.Serialization.SerializationException: The data contract type 'Customer' cannot be deserialized because the required data members 'id, name, country' were not found.
Why did this happen? Because the default implementation in .NET expects to use fields instead of properties, in contrast to almost everything else in .NET land. But armed with this knowledge, simply remove those property getters and setters from your member definitions, and you get regular fields.
Remember that if your JSON contains null values and/or optional return fields, be sure to mark your class fields as nullable types, such as "int?" or "bool?".
Good luck!