Search code examples
c#jsonc#-4.0javascriptserializeranonymous-objects

How to serialize anonymous object to JSON without including property name


I have the following code:

///<summary>
///In this case you can set any other valid attribute for the editable element. 
///For example, if the element is edittype:'text', we can set size, maxlength,
///etc. attributes. Refer to the valid attributes for the element
///</summary>
public object OtherOptions { get; set; }
public override string ToString()
{
   return this.ToJSON();
}

I need to get the anonymous object from the OtherOptions property and serialize each property of the anonymous object as it were from the main object.

E.g.:

OtherOptions = new { A = "1", B = "2" }

If I serialize it, it will be (or something like this):

OtherOptions: {
A: "1",
B: "2"
}

Is it possible to have A and B at the same level of OtherOptions without explicitly removing it.


Solution

  • Ok this is just ugly and I don't recommend doing it but it does what you want...

    Essentially, it creates a Dictionary of just the properties you want and then serializes that dictionary.

        static void Main(string[] args)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
    
            var obj = new {Prop1 = "val1", OtherOptions = new {A = "1", B = "2"}};
    
            IDictionary<string, object> result = new Dictionary<string, object>();
            foreach (var kv in GetProps(obj))
            {
                if (!kv.Key.Equals("OtherOptions"))
                    result.Add(kv);
            }
            foreach (var kv in GetProps(obj.OtherOptions))
            {
                result.Add(kv);
            }
            var serialized = serializer.Serialize(result);
        }
    
        static IEnumerable<KeyValuePair<string, object>> GetProps(object obj)
        {
            var props = TypeDescriptor.GetProperties(obj);
            return
                props.Cast<PropertyDescriptor>()
                     .Select(prop => new KeyValuePair<string, object>(prop.Name, prop.GetValue(obj)));
        }
    

    serialized becomes

    {"Prop1":"val1","A":"1","B":"2"}
    

    You could use an attribute on the field you want to ignore and then check for that attribute in the GetProps method and not return if exists.

    Again, I do not recommend doing this.