Let's say that there is a simple interface:
public interface ISerialize { string FirstProp { get; set; } string SecondProp { get; set; } }
which is implemented by the classes:
public class Class1 : ISerialize { public string FirstProp { get; set; } public string SecondProp { get; set; } public string ThirdProp { get; set; } } public class Class2 : ISerialize { public string FirstProp { get; set; } public string SecondProp { get; set; } public string FourthProp { get; set; } }
at the moment (which is not intended for long-term stability) I have a web page that looks like this: http://jsfiddle.net/SBbPT/ , where each text field corresponds to a property of a Class1 or Class2 object, and the Add to batch
link adds object to the JavaScript array and the Submit batch
button sends the JSON string to the string object web service. Currently, the following JS determines which type is created by Class1
or Class2
:
$(document).ready(function () { var iSerialize = []; $('#btnSubmit').click(function () { //creates Class1 object if ThirdProp is present if ($('#txt3').val().length > 0) { var class1 = { FirstProp: $('#txt1').val(), SecondProp: $('#txt2').val(), ThirdProp: $('#txt3').val() } iSerialize.push(class1); } else { var class2 = { FirstProp: $('#txt1').val(), SecondProp: $('#txt2').val(), FourthProp: $('#txt4').val() }; iSerialize.push(class2); } $('input').val(''); }); $('#btnSubmitBatch').click(function () { var data = "{jsonString:'" + JSON.stringify(iSerialize) + "'}"; console.log(data); $.ajax( { type: "POST", url: "default.aspx/DataList", contentType: "application/json", dataType: "json", data: data, success: function (data) { console.log('the post was successful'); console.log(data.d); }, error: function (xhr) { console.log(xhr.status); } }); }); });
Currently, if the user leaves the FourthProp text field empty, a Class1 object must be created, and if the user leaves the ThirdProp text field empty, a Class2 object must be created. My current web service method is as follows:
[WebMethod] public string DataList(string jsonString) { var jss = new JavaScriptSerializer(); List<ISerialize> list = jss.Deserialize<List<ISerialize>>(jsonString);
In the current state, I get the error message: No parameterless constructor defined for type of DeserializeListOfInterfaceTypes.ISerialize.
This can be avoided, and the program will work by making the List<ISerialize>
list of one of the specific types. Therefore, in this case, the presence of the ThirdProp
or FourthProp
determines whether the object should be Class1
or Class2
, respectively. How can I use the properties of a JavaScript object to determine which C # object to create?