forum

Home / DeveloperSection / Forums / How to serialize list property of a dynamic object

How to serialize list property of a dynamic object

Anonymous User317813-May-2013
Hi Everyone!

I have an issue with serialization for a WCF service (JSON output). I use dynamic object to return light JSON for my REST service.

This code return an empty result (impossible to serialize):

public DynamicJsonObject DoWork()
{
    dynamic result = new DynamicJsonObject();
    result.values = new List<int>() { 1, 2 };
}
but this code works perfectly

public DynamicJsonObject DoWork()
{
    dynamic result = new DynamicJsonObject();
    result.values = 1;
}
My DynamicJsonObject class is :

[Serializable]
public class DynamicJsonObject : DynamicObject, ISerializable
{
    private IDictionary<String, Object> Dictionary { get; set; }

    public DynamicJsonObject()
    {
        Dictionary = new Dictionary<String, Object>();
    }

    public DynamicJsonObject(SerializationInfo info, StreamingContext context)
    {
        Dictionary = new Dictionary<String, Object>();
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        var hasKey = Dictionary.ContainsKey(binder.Name);
        result = hasKey ? Dictionary[binder.Name] : null;
        return hasKey;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        Dictionary[binder.Name] = value;
        return true;
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        foreach (String key in Dictionary.Keys)
        {
            info.AddValue(key.ToString(), Dictionary[key]);
        }
    }
}

Thanks in advance!
Any help will be appreciated! 

Updated on 13-May-2013
I am a content writter !

Can you answer this question?


Answer

1 Answers

Liked By