views:

371

answers:

2

This is like a follow-up question to this one.

Basically what I'm doing is exposing some fields on some UI to some user.

These fields are established based on the parameter list of a given objects constructor. The user has the options to choose which object the UI is displaying by, oh I don't know, let's say picking an object from a drop down list or something.

Once the fields are filled in and the user submits, I know the Object Type I need to create, I know the parameter names its constructor takes and the parameter types. I get a JSON string on the server (C# code behind).

The object potentially can have many more properties, public or private, than what the constructor exposes.

Can I use still use JavaScript or JSON deserialization to get my object if the JSON string doesn't contain data for all properties?

I'm not sure if I can specify default values somehow by property attributes or something...

Thanks.

+1  A: 

The DataContract deserializer doesn't use the type's constructors when populating the object at all. It actually populates the object using the fields/setters/getters. Also, if you don't supply values for some of the properties they will initialize to their default value unless you wire up DataContract events such as OnDeserializing, OnDeserialize, etc. So for example if the type has a property called FirstName of type string (obviously) and the json doesn't have anything defined for a FirstName, when you deserialize you will get null as the default value since you did not supply this field.

Ralph
+1  A: 

Json.NET supports creating a type via a parametrized constructor provided there is only one constructor and the parameter names match the names of the properties on the JSON object.

James Newton-King