lundi 12 janvier 2015

Reflection of WCF's deserialized JSON Classes

I have run in an interesting issue...


Imagine simple class hiearchy like this:



class ClassA
{
public ClassB RefClassB { get; set; }

public ClassA()
{
RefClassB = new ClassB();
}
}

class ClassB
{
public ClassC RefClassC { get; set; }

public ClassB()
{
RefClassC = new ClassC();
}
}

class ClassC
{
public int IntProperty { get; set; }
}


..and this code which iterates through the above hiearchy using .NET Reflection



private void button1_Click(object sender, EventArgs e)
{
ClassA instanceOfClassA = new ClassA();
GetProperties(c);
}

private void GetProperties<T>(T instance)
{
GetProperties(typeof(T), instance);
}

private void GetProperties(Type classType, object instance)
{
foreach (PropertyInfo property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
object val = property.GetValue(instance, null);
if (val == null)
{
// e.g. I put to text box property names
textBox1.Text += property.Name + Environment.NewLine;
}
else
{
GetProperties(property.PropertyType, val);
}
}
}


this works great if use the code in for example WinForms Application.


But the problem is, that I need to use this inside my WCF Ajax Service to loop through incoming JSON parameter, like this:



namespace AeviGateway.Service
{
[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "POST", BodyStyle=WebMessageBodyStyle.Bare)]
MyModel.JSONResponse MyMethod(MyModel.JSONRequest data);
}

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Service: IService
{

public MyModel.JSONResponse MyMethod(MyModel.JSONRequest data)
{
GetProperties(data); // Here is the problem - it seems like all subclasses would be null..
....
}
}
}


JSON is like this:



{
"header": {
"version": "1",
"token": "d1c2c5b4-c5c6-4a31-89a5-75d4db4acaae"
},
"request": {
"number": 10,
"SubObject": {
"UID": "320f324e-22cd-4bd3-9e58-d965749d1986",
"Number": 11,
"Text": "something"
}
}
}


..is called from JavaScript AJAX. Of course, the MyModel.JSONRequest is defined exactly to reflect the JSON object. The problem is - the method to iterate through hiearchy doesn't work. It doesn't step into sub classes..which is strange because the same code works in my testing WinForms application.


Any help, comment, tip, idea...would be appreciated. Thank you






Aucun commentaire:

Enregistrer un commentaire