2

In a project(in C#) that I am working on I have to use a JSON representation that also contains methods of serialized object. That is the reason why I have to implement my own serializer. The Serializer is quite simply implemented with reflection. My problem is that it must also be able to handle objects with "self-creating" properties that are of the same type as original object.

Example:

class ClassA  
{  
    private ClassA a;
    public ClassA A  
    {  
        get
        {
            if (a == null)
                a = new ClassA();
            return a;  
        }  
    }  
}

Everytime I iterate over Properties new object (a) is created, and this way the Serializer ends up in an infinite recursion.

Any idea how to avoid this? Any suggestions are appreciated.

JeFf
  • 346
  • 5
  • 16

1 Answers1

0

Create an attribute that marks properties you don't want to touch during serialization. Only serialize properties without that attribute.

[AttributeUsage(AttributeTargets.Property)]
public class DoNotSerializeAttribute : Attribute
{
}

Usage:

class ClassA
{
    private ClassA a;

    [DoNotSerialize]
    public ClassA A
    {
        get
        {
            if (a == null)
                a = new ClassA();
            return a;
        }
    }
}

When you determine the properties to serialize:

var properties = theType.GetProperties()
     .Where(x => x.GetCustomAttributes(typeof (DoNotSerializeAttribute), true).Length == 0);

If you can't modify the class, you could pass in an explicit list of properties to exclude, like:

PropertyInfo[] exclude = new[]{ typeof(ClassA).GetProperty("A") };    
var properties = typeof(ClassA).GetProperties().Except(exclude);
Andre Loker
  • 8,368
  • 1
  • 23
  • 36
  • Thanks for your answer but the problem is that I cannot edit that class because it is part of an .dll library that my program uses only as an interface. – JeFf Feb 14 '13 at 14:36
  • I've updated the answer, you'll have to provide the list of properties to exclude explicitly. – Andre Loker Feb 14 '13 at 14:45
  • Well, that would definitely work. I just hoped to find some more universal solution. – JeFf Feb 15 '13 at 09:48
  • @JeFf well, a truly "universal" solution would have to determine somehow if it is a "bad" idea to access a property during serialization. But how do you determine that? You can of course create a heuristic to determine whether a property can potentially cause an infinite object graph by looking at the IL code of the properties. But that can be *very* sophisticated. – Andre Loker Feb 15 '13 at 15:36
  • I was afraid that there is no simple solution to this. I will probably change my recursive algorythm to keep information about the item that was serialized in step before and check if the currently serialized item is the same and in that case I will stop the recursion. It is ugly but it might just work. – JeFf Feb 15 '13 at 21:36