I have some JSON that I need to deserialize into a class. The class is composed of some simple getters and setters for some properties. Other properties are read only and are initialized through methods on that class. For example:
public class ReportDescription
{
public int Id { get; set; }
public int Title { get; set; }
public string Group { get; set; }
public IEnumerable<Param> RequiredParameters { get; }
public IEnumerable<Param> OptionalParameters { get; }
public void addParam(Param param) { /* add the param to the internal collection */}
}
The RequiredParameters
property returns IEnumerable and has no setter. To add required parameters to this object you would call addParam which performs some business logic and adds the parameter to the objects internal collection.
My JSON looks like this:
[
{
"ReportId": 1,
"DisplayName": "Report One",
"Group": "Group One",
"RequiredParameters": [],
"OptionalParameters": [],
},
{
"ReportId": 2,
"DisplayName": "Report Two",
"Group": "Group Two",
"RequiredParameters": ["Param1", "Param2"],
"OptionalParameters": [],
}
]
How would I deserialize this JSON into the class described above?
I attempted to use DataContractJsonSerializer which worked well for properties with a getter and a setter but was not able to find a way to customize it to invoke addParam when it encountered the RequiredParameters
property in the JSON. Is there a straightforward way to customize the DataContractJsonSerializer serialization?
Another option I considered was using JSON.NET to walk through the JSON and manually create a new ReportDescription and invoke it's methods. Is this possible to do with DataContractJsonSerializer or some other out of the box class in .NET 3.5?