HOW TO SERIALIZE LIST PROPERTY OF A DYNAMIC OBJECT

ben reitman

Total Post:96

Points:676
Posted by  ben reitman
C# 
C#
 2018  View(s)
Ratings:
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! 
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: How to serialize list property of a dynamic object

    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;

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!