JSON.net and self referential IEnumerable<T>

Jun 16, 2009 at 10:31 PM
Edited Jun 17, 2009 at 6:43 PM

how do i keep an object that implements IEnumerable<T> from serializing as a collection? I have a tree object that implements IEnumerable<T> to expose its child nodes, which are of the same type as the enclosing object. The object serializes fine when i don't have IEnumerable<T> implemented, but after i implement IEnumerable<T> it serializes as an array of empty arrays with length equal to the number of child nodes in the object. I've tried overriding the JsonConverter, but whenever i do i can't seem to get the default Deserialization behavior to work, since that still works even after implementing IEnumerable. what's the best approach for this?

example code for what i want to do follows:

[JsonObject(MemberSerialization=MemberSerialization.OptIn)]
public class Content : IEnumerable<Content>
{
    public List<Content> Children;
    [JsonProperty()]
    public strint Text;
        #region IEnumerable Members

        public IEnumerator GetEnumerator()
        {
            return Children.GetEnumerator();
        }

        #endregion

        #region IEnumerable<Content> Members

        IEnumerator<Content> IEnumerable<Content>.GetEnumerator()
        {
            return Children.GetEnumerator();
        }

        #endregion
}

basically, i want this to serialize to {"text":"blahblahblahblah"}, currently it serializes to [ [], [], [] ] if Children.Count == 3.

Coordinator
Jun 18, 2009 at 1:26 PM

It should now work as long as you have the JsonObject attribute. The source code on CodePlex has been updated.

Jun 18, 2009 at 4:11 PM

thanks a lot! it does exactly what i want it to now.