4

Let's say that there's a simple interface:

public interface ISerialize
    {
        string FirstProp { get; set; }
        string SecondProp { get; set; }

    }

that's 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 isn't meant for long-term stability) I have a web page that looks like: http://jsfiddle.net/SBbPT/ where each text box corresponds to a property in the Class1 or Class2 object and the Add to batch link adds the object a JavaScript array and the Submit batch button sends a JSON string to a webservice of the stringified object. For the time being the following JS determines which type, Class1 or Class2 is created:

 $(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 box blank, a Class1 object should be created and if the user leave the ThirdProp text box blank, a Class2 object should be created. My current web service method looks like:

[WebMethod]
        public string DataList(string jsonString)
        {
            var jss = new JavaScriptSerializer();
            List<ISerialize> list = jss.Deserialize<List<ISerialize>>(jsonString);
            //some members might have different properties
            //how to create a factory to create an instance based on the objects properties?
            return list[0].FirstProp;
        }

In its current state I get an error:No parameterless constructor defined for type of DeserializeListOfInterfaceTypes.ISerialize. This can be avoided and the program will work by making the List<ISerialize> a list of one of the concrete types. So in this case the presence of the property ThirdProp or FourthProp determines if the object should be Class1 or Class2, respectively. How can I use the properties of a JavaScript object to determine what C# object to create?

4 Answers 4

2

The problem is that the de-serializer has to instantiate classes to populate your list, not interfaces. But it has no way of knowing which class.

So your question boils down to: how to hint the deserializer which class to create for each JSON object?

There is no standard way of including a 'class' description in JSON (at least for now). You have to come up with your own rule (include a 'type' property, or probe the existing properties like you suggest). Of course the JSON framework has no way of knowing the rule, so it won't happen 'magically'.

Assuming you use Newtonsoft's JSON.net for serialization (if you don't -- you should). This exact question was asked and answered here:

How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

It basically comes down to overriding a JsonConverter.

2

You can solve this in two ways:

  1. Write a custom serializer, which will know your specific requirements and have logic about what exactly type to instantiate.
  2. Change the object model of your server, depending on the semantics of your web application.

If you take approach 1, instead of the JavaScriptSerializer, you should implement a custom one. Here is a starting point on how to do that: http://msdn.microsoft.com/en-us/library/ty01x675.aspx

If you decide to change your object model, you need to make sure that it works with the default JavaScriptSerializer, which wants specific types to instantiate. Now, depending on the semantics, Class1 and Class2 may be similar to each other (inheritance). In that case you can extract the properties which currently are included in the interface into a base class, and make whatever needs to be overriden virtual. Then Class1 and Class2 will override the properties, but they will still be defined in the base class, and the serializer will be able to create an instance of that class. Instead of the interface, you should give the base class as a type to the serializer. If Class1 and Class2 don't share any behavior, you can still create a base class to serve only for serialization. Of course this depends on the semantics, about which I don't know anything.

1
+200

If you want to keep using JavaScriptSerializer, then you can write a custom JavaScriptTypeResolver:

public class CustomTypeResolver : JavaScriptTypeResolver
{
    public override Type ResolveType(string id)
    {
        return id == "class1" ? typeof(Class1) : typeof(Class2);
    }

    public override string ResolveTypeId(Type type)
    {
        return type == typeof(Class1) ? "class1" : "class2";
    }
}

and then construct your serializer as following:

var jss = new JavaScriptSerializer(new CustomTypeResolver());

Finally, you need to add this type information to the __type field in your JavaScript code:

$('#btnSubmit').click(function ()
{
    //creates Class1 object if ThirdProp is present
    if ($('#txt3').val().length > 0)
    {
        var class1 = { __type: "class1", FirstProp: $('#txt1').val(), SecondProp: $('#txt2').val(), ThirdProp: $('#txt3').val() }
        iSerialize.push(class1);
    }
    else
    {
        var class2 = { __type: "class2", FirstProp: $('#txt1').val(), SecondProp: $('#txt2').val(), FourthProp: $('#txt4').val() };
        iSerialize.push(class2);
    }
    $('input').val('');
});

However, if you don't want to add any other properties to your objects, then I would agree with jods's answer and use Newtonsoft's JSON.NET instead of JavaScriptSerializer.

1

The route I'd personally choose might be the following:

Create a class that can host any given input for Class1 plus Class2 such as

public class ClassInput
{
    public string FirstProp { get; set; }
    public string SecondProp { get; set; }
    public string ThirdProp { get; set; }
    public string FourthProp { get; set; }
}

Use this class as an argument for your web method.

Then decide on the server side which class should be created.

Have a method for each of Class1 and Class2 which creates that class and maps each property from ClassInput.

public Class1 CreateClass1(ClassInput input)
{
    Class1 output = new Class1();
    output.FirstProp = input.FirstProp;
    output.SecondProp = input.SecondProp;
    output.ThirdProp = input.ThirdProp;
    return output;
}

public Class2 CreateClass2(ClassInput input)
{
    Class2 output = new Class1();
    output.FirstProp = input.FirstProp;
    output.SecondProp = input.SecondProp;
    output.FourthProp = input.FourthProp;
    return output;
}

Using AutoMapper can save you some code here if you have many classes / properties.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.