Home > DeveloperSection > Forums > How to serialize list property of a dynamic object
ben reitman
ben reitman

Total Post:96

Points:676
Posted on    May-13-2013 2:19 AM

 C# C# 
Ratings:


 1 Reply(s)
 1656  View(s)
Rate this:
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! 


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    May-13-2013 9:25 AM

Hi Ben!

You can serialize list property of a dynamic object as following. 

List<UserDetails> list = new List<UserDetails>();

"UserDetails" is class name it has some properties for serialization you can use this code.

var objSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = objSerializer.Serialize(list);
return list;


Don't want to miss updates? Please click the below button!

Follow MindStick