Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi;

I want to return a MobileResult class from my WCF Rest web service on every OperationContract that return value.

I can do this with classes that has no class list inside of it. But when I return a class that has class list inside of it it doesn't serialize the class.

So, how can I return a class that has class list inside of it? Or can I do this?

Thank you.

What I have tried:

My MobileResult class;

C#
[KnownType(typeof(SomeClass))]
[KnownType(typeof(AnotherClass))]
[DataContract]
[Serializable]
public class MobileResult
{
    [DataMember]
    public bool result { get; set; }
    [DataMember]
    public object data { get; set; }

    public MobileResult(bool res, object obj)
    {
        result = res;
        data = obj;
    }
}


My SomeClass, this class can serialize perfectly;

C#
public class SomeClass
{
    public int ID { get; set; }
    public string Name { get; set; }
}


My AnotherClass, this class doesn't serialize;

C#
public class AnotherClass
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public virtual ICollection<SomeClass> Classes{ get; set; }

        public AnotherClass{ Classes = new HashSet<SomeClass>(); }
    }


Operation Contract;

C#
[OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetAnotherClass/{number}")]
        MobileResult GetAnotherClass(string number);


C#
public MobileResult GetAnotherClass(string number)
        {
            try
            {
                AnotherClass aClass = new AnotherClass();
                aClass.ID = 5;
                aClass.Title = "MyTitle";
                aClass.Classes = GetClasses();
 
                return new MobileResult(true, aClass);
            }
            catch
            {
                return null;
            }
        }
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900