سؤال

I'm trying to use ServiceStack.Redis and i notice that when i store an object with members that are object that inheritance from another object and try to get it later on i get null.

I checked and found that ServiceStack.Redis is using ServiceStack.JsonSerializer so I've tried to create a test case:

class Program
{
    public class ClassA
    {
        public string Id;

        public Dictionary<string, ClassB> dic = new Dictionary<string, ClassB>();
    }

    public class ClassB
    {
        public string Id;   
    }

    public class ClassC : ClassB
    {
        public object C;
    }

    public class ClassD
    {
        public string Id;
    }

    static void Main(string[] args)
    {
        ClassA t = new ClassA();
        t.Id = Guid.NewGuid().ToString("n");
        t.dic.Add("AAA", new ClassC());
        t.dic["AAA"].Id = Guid.NewGuid().ToString("n");
        ((ClassC)t.dic["AAA"]).C = new ClassD();
        ((ClassD)((ClassC)t.dic["AAA"]).C).Id = Guid.NewGuid().ToString("n");

        ServiceStack.Text.JsConfig.IncludeNullValues = true;
        ServiceStack.Text.JsConfig.IncludePublicFields = true;
        ServiceStack.Text.JsConfig.IncludeTypeInfo = true;
        ServiceStack.Text.JsConfig.MaxDepth = int.MaxValue;

        Console.WriteLine("before SerializeToString data is:");
        if (string.IsNullOrEmpty(((ClassD)((ClassC)t.dic["AAA"]).C).Id))
        {
            Console.WriteLine("wrong");
        }
        else
        {
            Console.WriteLine("right");
        }

        string a = JsonSerializer.SerializeToString<ClassA>(t);

        ClassA t2 = JsonSerializer.DeserializeFromString<ClassA>(a);

        Console.WriteLine("after SerializeToString data is:");
        if (((ClassC)t2.dic["AAA"]).C == null ||
            string.IsNullOrEmpty(((ClassD)((ClassC)t2.dic["AAA"]).C).Id))
        {
            Console.WriteLine("wrong");
        }
        else
        {
            Console.WriteLine("right");
        }

        Console.ReadLine();
    }
}

I could find a simpler case when its not working...

As you can see ClassC has a member of type object and the class is inheriting from ClassB (if you remove the inheritance or give the member another type it will work).

Before serialize the data is "right" and after deserialize the data is "wrong" -> the member is null.

Can you please help me with that?

هل كانت مفيدة؟

المحلول

By default ServiceStack only serializes public properties. To serialize public fields as well you need to set:

JsConfig.IncludePublicFields = true;

Also if you want to use inheritance you need to make the sub class abstract or an interface. See this answer for more info.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top